This might be a stupid question, but is it possible to assign some values to an array instead of all? To clarify what I want:
If I need an array like {1,0,0,0,2,0,0,0,3,0,0,0}
I can create it like:
int array[] = {1,0,0,0,2,0,0,0,3,0,0,0};
Most values of this array are '0'. Is it possible to skip this values and only assign the values 1, 2 and 3? I think of something like:
int array[12] = {0: 1, 4: 2, 8: 3};
An alternative way to do it would be to give default value by
memset
for all elements in the array, and then assign the specific elements:Standard C17
The standard (C17, N2176) has an interesting example in § 6.7.9(37):
Example
Output:
In C, Yes. Use designated initializer (added in C99 and not supported in C++).
Above initializer will initialize element
0
,4
and8
of arrayarray
with values1
,2
and3
respectively. Rest elements will be initialized with0
. This will be equivalent toThe best part is that the order in which elements are listed doesn't matter. One can also write like
But note that the expression inside
[ ]
shall be an integer constant expression.Here is my trivial approach:
However, technically speaking, this is not "initializing" the array :)