Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize only few elements of an array with some values?

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}; 
like image 961
kaetzacoatl Avatar asked Aug 09 '16 20:08

kaetzacoatl


People also ask

Can arrays be partially initialized?

If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. The same applies to elements of arrays with static storage duration. (All file-scope variables and function-scope variables declared with the static keyword have static storage duration.)

How do you initialize an array with all elements 0?

Using Initializer List. int arr[] = { 1, 1, 1, 1, 1 }; The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.


1 Answers

Is it possible to skip this values and only assign the values 1, 2 and 3?

In C, Yes. Use designated initializer (added in C99 and not supported in C++).

int array[12] = {[0] = 1, [4] = 2, [8] = 3};   

Above initializer will initialize element 0, 4 and 8 of array array with values 1, 2 and 3 respectively. Rest elements will be initialized with 0. This will be equivalent to

 int array[12] = {1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0};    

The best part is that the order in which elements are listed doesn't matter. One can also write like

 int array[12] = {[8] = 3, [0] = 1, [4] = 2};  

But note that the expression inside [ ] shall be an integer constant expression.

like image 50
haccks Avatar answered Sep 21 '22 10:09

haccks