Search code examples
cmultidimensional-arrayinitializationlanguage-lawyer

Does C fill the remainder of a multidementional array with 0?


In a Korean government examination, (1) was a correct statement.

Choose the wrong statement for the following two-dimensional array in C:
int mat[3][4]={1,2,3,4,5,6};
(1) The value of mat[2][2] is 0.

I had been thinking that C does not fill integer arrays with 0's, so I tried to look up the specification, but document was too big. This answer (screenshot below for quick viewing, full text is in the link) seems to be saying that incomplete initialisation is implied to be 0, but is it guaranteed by the C specification?

enter image description here


Solution

  • From the C Standard (6.7.9 Initialization):

    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; all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

    and

    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 pointer type, it is initialized to a null pointer;

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

    — if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

    — if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

    So all elements of the array mat that are not initialized explicitly are initialized implicitly by zeroes.

    int mat[3][4]={1,2,3,4,5,6};
    

    As a result in the above declaration mat[2][2] is equal to 0.

    Have I passed the Korean government examination?:)