![]() |
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 !! |
Re: Doubt in C pointer concept
Quote:
dest = "HiHello\0"; |
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.
|
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"; |
| All times are GMT +5.5. The time now is 05:18. |