1

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?

Community
  • 1
  • 1
jobi
  • 21
  • 2

3 Answers3

8

When you write char *str = "abcde"; you make a char pointer to a string literal, which you are not allowed to modify.

When you write char str[] = "abcde"; you make a char array and copy a string literal into it. This is just a normal char array 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.

Flexo
  • 87,323
  • 22
  • 191
  • 272
2
char *str = "abcde";

str is a pointer to char that points to a string literal. String literals are stored in read only memory. You can't modify them.

char str[] = "abcde";

The string literal "abcde" is copied into the array str. So you can modify it.

Bertrand Marron
  • 21,501
  • 8
  • 58
  • 94
1

char * is pointer to char (string literal) and char [] is an array of char. You can't modify string literal but you can modify char array.

hari
  • 9,439
  • 27
  • 76
  • 110