Array Array Initialization - Problem

Well, I know that in C ++ a - let it be said that a 2-dimensional array can be initialized as follows:

int theArray[5][3] = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}, {13,14,15} }; 

Now, if I want to use pre-existing arrays as theArray elements?

for example

 // A, B, C, D,... have already been declared as : // `const U64 A[] = { 1,2,3,4 };` etc... const U64 multiDimArray[12][64] = { A, B, C, D, E, F, G, H, I, J, K, L }; 

This one throws an error though:

 cannot initialize an array element of type 'const U64' (aka 'const unsigned long long') with an lvalue of type 'const U64 [64]' 

I see the point, but I hope you can see mine.

Is there a workaround so I can easily achieve the same? (Any suggestion - perhaps using Boost? - welcome)

+8
c ++ c arrays multidimensional-array clang
source share
3 answers

I can understand why this is useful, however, in C, using only the name of the array variable, will return the address of the array in memory. The compiler does not know what is actually stored in during compilation, so this will not work.

Alternatively, you can use memcpy and copy the elements into an array (but then it will not be const ), or you can use #define A { 1, 2, 3, 4 } , and then maybe do something like

 #define A_val { 1, 2, 3, 4 } #define B_val { 5, 6, 7, 8 } const U64 multiDimArray[12][64] = { A_val, B_val, // and so on and so forth } const U64 A[4] = A_val; // if you need this const U64 B[4] = B_val; // you can do it like this 
+5
source share

If you are using C ++ 11, the initializer list for array is flexible:

 std::array< array<U64, 64>, 12> multiDimArray = { A, B, C, D, E, F, G, H, I, J, K, L }; 

will work fine if A..L std::array<64, U64> .

In the c-style array, there are no utility arrays. Click here for official reference.

"The size and efficiency of the array for a number of elements is equivalent to the size and efficiency of the corresponding C-style array T [N]." (From the link)


I said "flexible" since you can use a mixed list of initializers, for example:

 std::array<int, 3> first_row = {1,2,3}; std::array<array<int, 3>, 2> a={ first_row, {2, 2, 2} }; 

You can use this as a fixed-size array with the same operations:

 a[1][2]=2; a[0][1]=1; a[0][2]=3; 
+4
source share

You can use the fact that a two-dimensional array is actually a one-dimensional array of pointers to your advantage. Subsequent initialization should work for you.

 const U64 *multiDimArray[12] = { A, B, C, D, E, F, G, H, I, J, K, L }; 
+1
source share

All Articles