Possible Duplicates:
Difference between char *str="STRING" and char str[] = "STRING"?
Need some help with C programming
while this snip gets segmentation fault
int main(void) {
char* str ="abcde";
str[strlen(str)-1] ='\0';
printf("%s",str);
return 0;
}
If I put
char str [] ="abcde"; instead of the pointer that works perfectly, do you have an idea why so?
When you write
char *str = "abcde";you make acharpointer to a string literal, which you are not allowed to modify.When you write
char str[] = "abcde";you make achararray and copy a string literal into it. This is just a normalchararray so you are free to modify it.It is undefined behaviour to modify a string literal. This is a deliberate design decision that allows string literals to be placed in special read only sections of the output program. In practice many compliers and platforms do this (marking it read only means you need only one copy of the strings in memory, even if there is more than one instance of the program running). This leads to the behaviour you observed on your platform.