9

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

6
  • Yes, the first element only, the rest is filled with 0. Commented Jun 2, 2016 at 16:29
  • If you're looking for a standards-compliant method, no, there's not. If you're using GCC, and are ok with implementation-defined solutions: stackoverflow.com/a/207702/3470630 Commented Jun 2, 2016 at 16:37
  • What's wrong with a one-line call to memset? Commented Jun 2, 2016 at 16:38
  • 3
    How to initialize all members of an array to the same value Commented Jun 2, 2016 at 16:42
  • 3
    @michaelsnowden memset sets all the bytes to the same value, so initializing even a single int to 333 is not possible with a one-line call to memset. Commented Jun 2, 2016 at 16:43

4 Answers 4

7

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} };
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

3

If I understood you correctly, you need to take a look at designated initializers designated initializers

This is a GNU C extension with which you can initialize values of an array in one show.

int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };

This will initialize 1 to elements 0 to 9, 2 to elements 10 to 99, 3 to 100th element.

And in your case, it is like

MY_S a[666] = { [0 ... 665] = {333, 666.0} };

Comments

2

This will initialize the first struct, and everything else is zeroed.

See ANSI C89 3.5.7 Initialization:

[...]

float z[4][3] = { { 1 }, { 2 }, { 3 }, { 4 } };

initializes the first column of z as specified and initializes the rest with zeros.

[...]

There is, unfortunately, no way to initialize the array without looping over it, calling memset or by any other means.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.