views:

82

answers:

3

Do these two lines of code achieve the same result? If I had these lines in a function, is the string stored on the stack in both cases? Is there a strong reason why I should use one over the other, aside from not needing to declare the null terminator in the first line of code?

char  s[] = "string";
char* s   = "string\0";
A: 

First hit on Google.

http://www.lysator.liu.se/c/c-faq/c-2.html

vichle
+9  A: 

No, those two lines do not achieve the same result.

char s[] = "string" results in a modifiable array of 7 bytes, which is initially filled with the content 's' 't' 'r' 'i' 'n' 'g' '\0' (all copied over at runtime from the string-literal).

char *s = "string" results in a pointer to some read-only memory containing the string-literal "string".

If you want to modify the contents of your string, then the first is the only way to go. If you only need read-only access to a string, then the second one will be slightly faster because the string does not have to be copied.


In both cases, there is no need to specify a null terminator in the string literal. The compiler will take care of that for you when it encounters the closing ".

Bart van Ingen Schenau
Also, the second one is only allowed for horrible legacy reasons. You should use `const char *s = "string";`
Steve Jessop
@Steve: For C++ I would completely agree with you. For C, I tend to give a bit more leeway, because in practice there are too many ways that the `const` gets into your way. (That is also known as const-poisoning)
Bart van Ingen Schenau
@Bart: If I'm using dodgy libraries, I agree with you (sometimes). If the code is under my control then I fix it so that `const` doesn't get in my way. The alternative is to take copies of strings that have to be passed as non-const parameters to dodgy APIs. Sometimes that's do-able, for instance if the string being passed is a literal defined close to the call, or as a global, then just use the first of the two options above. Other times it's a PITA, in which case you could either take the hit of strdup, or cast away `const` (which is "unsafe", but then you're already using an "unsafe" API).
Steve Jessop
The second version is very useful for arrays of constant strings of different lengths or inclusion of constant strings within structures (though I tend to use `const` in the declaration if I can).
nategoose
A: 

The difference between these two:

char a[] = "string";
char* b = "string";

is that a is actually a static array on stack, while b is a pointer to a constant. You can modify the content of a, but not b.

Let_Me_Be