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)?
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.
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 } };
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];
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.
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} };
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With