How to initialize an array?

I have a three-dimensional array, how to initialize it to the default value without 3 loops.

dummy[4][4][1024] 

how can i initialize all elements to 12?

+4
source share
3 answers

Since the 3rd array is a continuous block of memory, you can view it as a 1-dimensional array

 int i, *dummy2 = &dummy[0][0][0]; for(i = 0; i < 4*4*1024; ++i) dummy2[i] = 12; 
+10
source

Come on guys, let this do a simple way that always works:

 for(int i = 0; i &lt 4; i++) { for(int j = 0; j &lt 4; j++) { for(int k = 0; k &lt 1024; k++) { dummy[i][j][k] = 12; } } } 
+7
source

The default initialization for all zeros is as follows:

 unsigned dummy[4][4][1024] = { 0 }; 

If you want to initialize individual elements (and all others to zero), do this

 unsigned dummy[4][4][1024] = { { { 5 }, { 0, 4 } } }; 

and if your compiler knows that C99 uses designated initializers

 unsigned dummy[4][4][1024] = { [3] = { [2] = { [0] = 7 }, [1] = { [2] = 3, [1] = 4 } } }; 

and if you really insist on using all 12 , just repeat 12 16384 times :)

+5
source

Source: https://habr.com/ru/post/1414455/


All Articles