Normally, if you do the following:
int * i = &someint;
It’s just a pointer to a variable.
But, when you do
char * str = "somestring";
it automatically turns it into an array. Is it the pointer which is doing this, or is it just syntactic sugar for initialization syntax?
No, the string literal
"somestring"is already a character array, almost certainly created by your compiler.What that statement is doing is setting
strto point to the first character. If you were to look at the underlying assembler code, it would probably look like:In a large number of cases, an array will decay to a pointer to the first element of that array (with some limited exceptions such as when doing
sizeof).By way of example, the following C code:
when compiled with
gcc -Sto generate x86 assembly, gives us (with irrelevant cruft removed):You can see that the address of the first character,
.LC0, is indeed loaded into thesomestrvariable. And, while it may not be immediately obvious.stringdoes create an array of characters terminated by the NUL character.