简体   繁体   中英

How to initialize an array of 2d array statically in c++

Let's say I have these declared statically outside of main.

const int R = 5;
const int C = 3;

char zero[R][C] = {' ', '-', ' ',
                   '|', ' ', '|',
                   ' ', ' ', ' ',
                   '|', ' ', '|',
                   ' ', '-', ' '};    

char one[R][C] = {' ', ' ', ' ',
                  ' ', ' ', '|',
                  ' ', ' ', ' ',
                  ' ', ' ', '|',
                  ' ', ' ', ' '};

char two[R][C] = {' ', '-', ' ',
                  ' ', ' ', '|',
                  ' ', '-', ' ',
                  '|', ' ', ' ',
                  ' ', '-', ' '};

and I want to do something like:

char ho[3][R][C] = {zero, one, two}

So I can do ho[0], ho[1], ho[2] to get the corresponding 2d array. AND do ho[0][1][2] to get the entry in the array. (I don't want to do ho[0][1*2])

I am really confused what the data type of 'ho' should be.

I googled and tried

char (*ho[3])[R][C] = {(char(*)[R][C])zero, (char(*)[R][C])one, (char(*)[R][C])two};

but this doesn't seem to achieve what I want.

I can think of couple of choices.

Use a typedef to a pointer to 2D arrays. Then use an array of the typedef .

typedef char (*ptr)[C];
ptr ho[3] = {zero, one, two};

You can intialize the entire 3D array in one humongous statement.

const int R = 5;
const int C = 3;

char ho[3][R][C] =
   {
      {' ', '-', ' ',
       '|', ' ', '|',
       ' ', ' ', ' ',
       '|', ' ', '|',
       ' ', '-', ' '},  

       {' ', ' ', ' ',
        ' ', ' ', '|',
        ' ', ' ', ' ',
        ' ', ' ', '|',
        ' ', ' ', ' '},

        {' ', '-', ' ',
        ' ', ' ', '|',
        ' ', '-', ' ',
        '|', ' ', ' ',
        ' ', '-', ' '}
  };

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