jbl
jbl

Reputation: 582

Array of structure, designated initializer implication

I already know that:

1) array "partial initialization"

int array[10] = {1};

results in initialising array[0] with value 1, and all other array values with 0.

2) designated initializers

struct metadata {
    int val0;
    int val1;
    char *name;
};

void func(void){
    struct metadata my_metadata = { .val0 = 1 };

Results in initialising my_metadata.val0 with 1, my_metadata.val1 with 0 and my_metadata.name with NULL.

3) Here comes the question:

struct metadata {
    int val0;
    int val1;
    char *name;
};

void func(void){
    struct metadata my_metadata_array[2] = { {.val0 = 1} };

What will be the resulting operation of this ?

Bonus question 1: could someone point me to the reference documentation for "partial initialisation" (I do not know if it is a compiler extension or part of a specific standard version) ?

Bonus question 2: same than bonus question 1 for "designated initializers".

Upvotes: 3

Views: 360

Answers (2)

imreal
imreal

Reputation: 10348

Just like in "partial initialization", the first metadata element will be initialized with val0 element set to 1, everything else in that element and the second element will be default initialized (or the same as objects with static duration).

Bonus 1: It has been part of the standard for a while

C Standard 6.7.9-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.

Bonus 2: It is part of C99

C Standard 6.7.9-7

If a designator has the form . identifier then the current object (defined below) shall have structure or union type and the identifier shall be the name of a member of that type.

Upvotes: 4

gsamaras
gsamaras

Reputation: 73366

Yes (you got the way of thinking fine), that's the result, it will set that variable to 1 and default initialize the rest of them.

Example:

#include <stdio.h>

struct metadata {
    int val0;
    int val1;
    char *name;
};

int main(void){
    struct metadata my_metadata_array[2] = { {.val0 = 1} };
    printf("%d %d %s\n", my_metadata_array[0].val0,  my_metadata_array[0].val1,  my_metadata_array[0].name);
    printf("%d %d %s\n", my_metadata_array[1].val0,  my_metadata_array[1].val1,  my_metadata_array[1].name);
    return 0;
}

Output:

1 0 (null)
0 0 (null)

Upvotes: 1

Related Questions