简体   繁体   English

如何在C ++中静态初始化2D数组的数组

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

Let's say I have these declared statically outside of main. 假设我在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. 所以我可以做ho [0],ho [1],ho [2]来获得对应的2d数组。 AND do ho[0][1][2] to get the entry in the array. AND执行ho [0] [1] [2]以获取数组中的条目。 (I don't want to do ho[0][1*2]) (我不想做ho [0] [1 * 2])

I am really confused what the data type of 'ho' should be. 我真的很困惑“ ho”的数据类型应该是什么。

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. 使用typedef指向2D数组的指针。 Then use an array of the typedef . 然后使用typedef的数组。

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

You can intialize the entire 3D array in one humongous statement. 您可以在一个庞大的语句中初始化整个3D数组。

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

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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