Search code examples
cstructinitialization

Partial initialization for an array of structures in C


While revising my C knowledge, I stumbled into the following example:

#include <stdio.h>

/* Just a simple structure */
typedef struct lab {
    int num;
    char *str;
} bal;

int main (void) {
    /* Declare and _partially_ initialize an array of the structure above... */
    bal struct_array[10] = { {0, NULL} };

    /* Question: what does _exacly_ happen to the other 9 members of the array? */ 
    return 0;
};

The comment in the code should be enough to provide my question. In other words, what does it happen if we partially initialize an array of structs? Sure, I know that (at least) for C++11 there is the default initialization. But does it hold for pure C, too? If yes, is it true for all the standards (from C89 on), or just for some in particular? Thank you.


Solution

  • If an array or struct is only partially initialized, any containing objects without an explicit initializer are set to 0 or NULL.

    Partial initialization is covered in section 6.7.9p21 of the C11 standard:

    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.

    And initialization of objects with static storage duration are covered in section 6.7.9p10:

    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 in your particular case, all array elements will have the num member set to 0 and the str member set to NULL.