Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Doubt in C pointer concept (http://www.go4expert.com/forums/doubt-c-pointer-concept-t4463/)

vila8 29May2007 14:50

Doubt in C pointer concept
 
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 !!

tailhook123 31May2007 03:05

Re: Doubt in C pointer concept
 
Quote:

Originally Posted by vila8
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 !!

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";

karri 6Jun2007 01:28

Re: Doubt in C pointer concept
 
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.

DaWei 6Jun2007 05:13

Re: Doubt in C pointer concept
 
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."


All times are GMT +5.5. The time now is 10:10.