2

How does this work::

char Test1[8] = {"abcde"} ;

AFAIK, this should be stored in memory at Test1 as

a b c d e 0 SomeJunkValue SomeJunkValue

instead it get stored as:

a b c d e 0 0 0

Initializing only adds one trailing NULL char after the string literals but how and why all other array members are initialized to NULL ? Also, any links or any conceptual idea on what is the underlying method or function that does:char TEST1[8] = {"abcde"} ; would be very helpful. How is:

char Test1[8] = {"abcde"} ;

different from

char Test1[8] = "abcde" ;

?

  • 1
    Related & Good Read: [C and C++ : Partial initialization of automatic structure](http://stackoverflow.com/q/10828294/452307) – Alok Save Sep 26 '12 at 07:51

1 Answers1

8

Unspecified members of a partially initialized aggregate are initialized to the zero of that type.

6.7.9 Initialization

21 - If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

10 - [...] If an object that has static or thread storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero; [...]

For the array char Test1[8], the initializers {"abcde"} and "abcde" are completely equivalent per 6.7.9:14:

An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • @user1696837 it's up to the compiler. The compiler can emit instructions to copy data from `.rodata`, to assign stack locations directly, to initialize in a loop either directly or by calling `memset`, or optimise out the stack object entirely if possible. – ecatmur Sep 26 '12 at 08:19