LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Why is this happening...?? (https://www.linuxquestions.org/questions/linux-newbie-8/why-is-this-happening-720331/)

thelink123 04-20-2009 01:12 AM

Why is this happening...??
 
There is an important difference between these definitions:
Code:

char amessage[] = "now is the time"; /* an array */
char *pmessage = "now is the time"; /* a pointer */

amessage is an array, just big enough to hold the sequence of characters and '\0' that
initializes it. Individual characters within the array may be changed but amessage will always
refer to the same storage. On the other hand, pmessage is a pointer, initialized to point to a
string constant; the pointer may subsequently be modified to point elsewhere, but the result is
undefined if you try to modify the string contents.


Please explain to me why this difference occurs. It would be better if the explanation is based on the memory allocation.

thanks,
thelink

greplinux 04-20-2009 04:55 AM

Hi,

In the declaration

/* char *pmessage = "now is the time"; */

you are pointing to a string constant, which cannot be changed. That is why you are getting memory access error while trying to alter its contents.

Thanks,


All times are GMT -5. The time now is 02:55 AM.