0

Hi. Below are two pieces of code. This first one works fine:

char str[] = "Hello World";
    char *b;
    b = &(str[3]);
    *b = '3';
    printf("%s\n", str);

However this second one results in a segmentation fault.

char *str = "Hello World";
    char *b;
    b = &(str[3]);
    *b = '3';
    printf("%s\n", str);

The difference is in the definition of the variable str. Why does one method work fine and the other result in a segmentation fault? When is it best to use a str[] definition and the *str definition?

3
Contributors
2
Replies
5
Views
9 Years
Discussion Span
Last Post by WolfPack
0

The first is local data you can edit (since the array is local data).

The second is a local pointer to global, static (constant) data. You are not allowed to modify constant data.

If you have GNU C, you can compile with -fwritable-strings to keep the global string from being made constant, but this is not recommended.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.