Search code examples
c++initializationconstantsstatic-array

Initialization of a three dimensional static const array


I have a three dimensional static const array that is acting as a lookup table. Each cell of the array can return up to 8 separate numbers (each number is the corner of a cube - a voxel to be exact). So for example, MyStaticArray[0][1][1] might return 1,2,5,7. It can return a single number or a maximum of eight numbers, like so: 1,2,3,4,5,6,7,8.

I already have the lookup table prepared (on paper), my question is what the best way to store it? Initially I was going with a static const unsigned char[][][] but that is obviously not going to work in this case as the table can return more than one number (again, from 1-8).

My next solution was to return an unsigned char array. That is, static const unsigned char* [][][]. How do I initialize this (that is, how do I initialize the static const array to return to me unsigned char arrays that are also static so that I can access them without initializing a class)? Is there a better way?

I hope I was able to explain the question properly. If not, let me know and I will try to reword it and/or provide extra info.


Solution

  • You could pad each element up to the maximum length with dummy elements, and go with a 4D array:

    static const unsigned char x[M][N][P][8] = { { 1, 2, 5, 7, -1, -1, -1, -1 },
                                                 { 1, 2, 3, 4,  5,  6,  7,  8 },
                                                 ...
    

    or you could use individual bits as flags, e.g.:

    static const unsigned char x[M][N][P] = { 0x53, // Bits 0, 1, 4, 6 are set
                                              0xFF,
                                              ...
    

    If you find yourself needing more than 8 possibilities, upgrade to e.g. uint16_t or uint32_t.

    Which method you go with depends on what you intend to do with the data.