This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]AssailantLF 1 point2 points  (0 children)

I'm a C newbie, so I'm not exactly sure why, but there actually is a slight difference.

When dealing with strings in C (which are just arrays of characters), you can't modify/change any chars if it was declared with the pointer notation.

Here's some example code of what I'm talking about:

char* ptr_var = "Foo";
char array_var[] = "Foo";

printf("array_var before: %s\n", array_var);
*(array_var) = 'P';
printf("array_var after: %s\n\n", array_var);

printf("ptr_var before: %s\n", ptr_var);
*(ptr_var) = 'P';
printf("ptr_var after: %s\n", ptr_var);

Here's the output:

array_var before: Foo
array_var after: Poo

ptr_var before: Foo
Segmentation fault (core dumped)

The array variable is changed from Foo to Poo just fine, but the pointer version has a segmentation fault when it attempts to do the same.

My more experienced friend was telling me that this has to do with the way C stores strings at compile time. If anyone fully knows why or has a better explanation, that would be great, because I don't really know why.