1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Doubt in C pointer concept

Discussion in 'C' started by vila8, May 29, 2007.

  1. vila8

    vila8 New Member

    Joined:
    May 29, 2007
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi folks,

    I have been stuck with a problem for hours .Kindly help me out of this predicament.

    Consider the following code:


    char *dest;
    dest = (char*) malloc (10);
    dest = "HiHello";
    printf("\n the size of dest:%d", strlen(dest));
    *dest='A';

    The last line throws a segmentation fault while strlen of dest works.
    But the follwoing code works perfectly:

    char *dest;
    dest = (char*) malloc (10);
    strcpy(dest,"HiHello"); ---> Please note this change.
    printf("\n the size of dest:%d", strlen(dest));
    *dest='A';

    The latter snippet works fine but the former doesnt.I dont understand why.Can anyone please explain to me why this hassle !!
     
  2. tailhook123

    tailhook123 New Member

    Joined:
    May 23, 2007
    Messages:
    30
    Likes Received:
    0
    Trophy Points:
    0
    Sure... a char * is a pointer to a string of characters terminated by a \0. Strcpy tacks the null terminator on the end.. your original code using the '=' notation doesn't. You need to force the character just after the o in hello to be a null 0. Once that happens strlen knows where to stop. Its possible you could just make it:

    dest = "HiHello\0";
     
  3. karri

    karri New Member

    Joined:
    Jun 5, 2007
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    I think it is because as dest is a pointer initialised to point to a string constant if the contents of the string are modified the result is undefined. But in the second one u r writing the string in the memory allocated using malloc where as in the first case it is else where in the memory and is just pointed by dest.
     
  4. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    You cannot assign to an array using '=', with or without a trailing 0. When you see a statement like:
    Code:
    char *myString = "This is the string in question";
    you are seeing a compile-time initialization, done as a favor by the compiler. This occurs at compile time; it will not work at run time. See the pointer tutorial referred to in my signature, specifically the section, "Confustoids."
     

Share This Page