Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error using pointer to char instead of char array [duplicate]

Tags:

arrays

c

pointers

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.

like image 379
elios264 Avatar asked Jan 18 '23 21:01

elios264


2 Answers

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.

like image 177
NPE Avatar answered Mar 07 '23 04:03

NPE


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).

like image 45
Krizz Avatar answered Mar 07 '23 04:03

Krizz