Possible Duplicate:
Why does simple C code receive segmentation fault?
I am working in Ubuntu using the GCC compiler with C language; I have this program:
void foo(char *word)
{
//something stupid
*word = 'z';
}
int main()
{
char word1[] = "shoe";
char *word2 = "shoe";
foo(word1);
printf("%s", word1);
foo(word2);
printf("%s", word2);
}
So what's the difference? With the latter I get a segmentation fault
error.
The difference is that the first one is valid code, whereas the behaviour of the second one is undefined (since you are not allowed to modify a string literal). See the FAQ.
char word1[] = "shoe";
creates an array of 5 characters and copies the string literal "shoe" into it (which can be modified).
char *word2 = "shoe";
creates a pointer to the string literal "shoe" (which cannot be modified).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With