3

for arrays of type int or double, if the size of the array is bigger than the number of elements provided when the array is initialized (like a list), the rest of the elements in the array are defaulted to 0 right?

What happens when I initialize a character array with less elements than the size I provide? Like

char ch[10] = { 'h', 'e', 'l', 'l', 'o' };

Are the rest of the elements assigned any value? Or is it just garbage in memory?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Howard Wang
  • 472
  • 6
  • 18

1 Answers1

4

This declaration

char ch[10] = { 'h', 'e', 'l', 'l', 'o' };

is equivalent to this declaration

char ch[10] = { "hello" };

that in turn is equivalent to the following declaration

char ch[10] = "hello";

and all these declarations are equivalent to the following declaration

char ch[10] = { 'h', 'e', 'l', 'l', 'o', '\0', '\0', '\0', '\0', '\0', };

That is elements of the array that do not have explicit initializers are implicitly zero-initialized.

From the C Standard (6.7.9 Initialization)

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

...

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

and

19 The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;151) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335