whiteSkar
whiteSkar

Reputation: 1644

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.

Upvotes: 0

Views: 90

Answers (1)

R Sahu
R Sahu

Reputation: 206567

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] =
   {
      {' ', '-', ' ',
       '|', ' ', '|',
       ' ', ' ', ' ',
       '|', ' ', '|',
       ' ', '-', ' '},  

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

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

Upvotes: 1

Related Questions