Skip to content

C initialize array inside struct

Another article on initialization is likely to follow, but this is going to serve as a temporary go-to article for initializing structs (and more or less the same for unions).


typedef struct test
    int i;
    char c[2][5];
} test;

This can be initialized using:

test t = {10, {{'a','b','c','d','\0'}, { 0 }}};
// or
test t = {10, {{'a','b','c','d','\0'}, {'x','y','z','v','\0'}}};

The first one says initialize i to 10, the first string to abcd(\0) and the 2nd to all 0s, and the second one does the same as before, except that for the 2nd string it initializes it to xyzv(\0).

When initializing the array, as long as at least one element is specified within {}, then all the omitted are set to 0. Thus {0} sets the first to 0, and the rest to 0. This is a important distinction, as for example you can try the following:

int i[5] = {20};
int j;

for (j=0; j<5; j++)
    printf("%d\n", i[j]);

The result is 20 0 0 0 0

Posted in C/C++. Tagged with , , , , , .