Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 263
Silicomancer Avatar asked Jun 02 '16 16:06

Silicomancer


People also ask

How do you initialize an entire array with the same value?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

How do I initialize an array in a struct?

Here is how initialize the structure : struct str { char arr1[4]; // this string is limited to three characters plus null char arr2[4]; int num1[4]; int num2[4]; }; struct str select = { "Sam", "Joe", { 0, 1, 2, 3 }, { 4, 5, 6, 7 } };

How can we initialize an array in C language?

Array Initialization Using a Loop The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C. // declare an array. int my_array[5];

Can we initialize array in structure?

An array in a structure is declared with an initial size. You cannot initialize any structure element, and declaring an array size is one form of initialization.


2 Answers

In standard C, you'd need to repeat the initializer. In GCC, you can specify a range of elements to initialize with the same initializer, for example:

MY_S a[666] = { [0 ... 665] = {333, 666.0} };
like image 55
Ian Abbott Avatar answered Sep 18 '22 02:09

Ian Abbott


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).

like image 25
s7amuser Avatar answered Sep 21 '22 02:09

s7amuser