简体   繁体   中英

Create an array of 2D arrays

If I write the following in C++

uint8_t empty[2][2] = {{0,0},{0,0}};

and the try to create an array of those empty arrays,

uint8_t empty[][2][2] = {empty, empty, empty};

I get the warning that

error: array must be initialized with a brace-enclosed initializer

so how cold I initialize an array of 2 dim arrays?

If you must:

#define EMPTY {{0,0},{0,0}}
uint8_t empty[][2][2] = {EMPTY, EMPTY, EMPTY};

However, piling up raw arrays will make your code a mess in no time, if you ask me.

Better encapsulate your array in a class, so that callers can have a functional description of what you indend to do with it instead of coping with its implementation details.

You can declare the variables as pointers and allocate the memory dynamically.

uint8_t **empty=new uint8_t*[2];
empty[0]=new uint8_t[2];
empty[1]=new uint8_t[2];

uint8_t ***Empty=new uint8_t**[3];
int i,j;

for (i=0;i<2;i++)
    for (j=0;j<2;j++)
        empty[i][j]=0;

for (i=0;i<3;i++)
{
    *(Empty+i)=empty;
}


//do some work


//delete the allocated memory
delete []empty[0];
delete []empty[1];
delete []empty;
delete []Empty;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM