To initialize a char array, usually I write:
char string[] = "some text";
But today, one of my classmates said that one should use:
char string[] = {'s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't', '\0'};
I told him it is crazy to abandon readability and brevity, but he argued that initializing a char array with a string will actually create two strings, one asides in the stack and another in the read-only memory. When working with embedded devices, this can result in unacceptable waste in memory.
Of course, string initializers seems clearer, so I'll use them in my programs. But the question is, will a string initializer create two same string? Or string initializers are just syntax sugars?
char string[] = "some text";
is 100% equivalent to
char string[] = {'s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't', '\0'};
Your friend is confused: if string
is a local variable, then in both cases you create two strings. Your variable string
which resides on the stack and a read-only string literal which resides in read-only memory (.rodata
).
There is no way to avoid the read-only storage, since all data must be allocated somewhere. You cannot allocate string literals in thin air. All you can do is to move it from one read-only memory segment to another, which will give you the very same program size in the end anyway.
The former style is preferred in general, as it is more readable. It is indeed a form of syntactic sugar.
But it is also preferred because it might ease some compiler optimization known as "string pooling", which allows the compiler to store the string literal "some text"
in more memory-effective ways. If you initialize the string character-by-character, the compile may or may not realize that it is a read-only string constant.
After your edit, there is no difference between the two definitions. Both will produce an array of ten characters and initialized to the same contents.
This is actually easy to verify: First check what sizeof
gives you for the two arrays, then you can use e.g. memcmp
to compare both the arrays.
The second initialization is almost equal to the first, with once crucial difference: The second array is not terminated as a string.
The first creates an array of ten characters (including the terminator) and the second creates an array of nine characters. If you don't use the array as a string, then yes you will save once element with the second initialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With