Search code examples
carraysstructinitializationc99

Initialize an array of structs in C or C99 to all the same values


Lets assume the following in C or C99:

typedef struct
{
   int x;
   double y;
} MY_S;

MY_S a[666] = {333, 666.6};

Does this initialize the first object of the array only? If yes, is there a way to initialize ALL elements of the array to all the same values using that syntax (without calling a function/loop and without repeating the initializer)?


Solution

  • Quote from C99 standard section 6.7.8:

    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.

    I.e. Only the first element will be initialized to the supplied value while the others will be filled with zeros.

    There is no way (in standard C) other than a loop to initialize an array of complex structs (memset() can be used to initialize a block of memory with a specified value).