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";
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 ".
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.
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):
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.