问题
int main()
{
char a[] = "123454321";
}
"123454321"
is a string literal and a string literal sets aside memory storage. a
is defined by the statement which also causes memory storage. That is, this simple statement char a[] = "123454321";
causes two memory storage, one is for a
and the other is for "123454321"
. Is it right?
回答1:
Yes, that's right.
Note that the object on the right of the =
is not a string literal as such; it's an initialisation expression and the compiler is under no obligation to store it as though it were a string. It might break it up into pieces, or emit a series of immediate stores instead of copying the initial value, or even (in theory) emit code which decompresses a shortened version of the initial data. But however it is compiled, some memory will be occupied.
If it the compiler does choose to store the initial value as a string, that value will need to be immutable so it may be placed in read-only memory and/or be shared with a string literal with the same value. a
, on the other hand, is mutable and may be altered. So clearly it must have its own memory.
Finally, there is one case in which the compiler might not reserve ant space at all. It might optimise away either or both the unused array and the initial value if it can prove that no visible changes will result from the removal, as would be possible with the sample code in your question.
来源:https://stackoverflow.com/questions/65803496/does-array-initialization-with-a-string-literal-cause-two-memory-storage