Search code examples
c++carraysmultidimensional-arrayclang

Initializing Array of Arrays - Trouble


OK, I know that in C++ a - let's say 2-dimensional - array can be initialized this way :

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

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

E.g.

// 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 hopefully you can see mine.

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


Solution

  • I can see why this is useful, however, in C, using just the variable name of an array will return the address of the array in memory. The compiler has no idea as to what is actually stored at A during compile time, so this wouldn't work.

    As an alternative, what you could do is either use a memcpy and copy the elements into the array (but then it won't be const), or you could use a #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