In C, can I initialize a string in a pointer declaration the same way I can initialize a string in a char array declaration?

20,370

Solution 1

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

Solution 2

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.

Solution 3

In addition to the other answers I will try to explain why you cannot modify the *s variable later on the program flow.

Conceptually when a program is loaded in memory it has 3 areas (segments):

  • code segment: the text of your program is stored here (it is a read-only area)
  • data segment: contains any global or static variables which have a pre-defined value and can be modified
  • stack segment: here are loaded the functions as they are called. The set of values (a stack frame) pushed on the stack for every function call which contains the return address off the function and the local variables.

In your case the s[] variable is a local variable (array), in the main() function, which is initialized with the value "string" . Thus, it is stored on the stack and can be modified.

The *s variable is a pointer which points to the address of "string\0", a constant located in the code segment. Being a read-only area, you cannot modify it's contents.

Share:
20,370
aoeu
Author by

aoeu

Updated on June 28, 2020

Comments

  • aoeu
    aoeu almost 4 years

    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";