0

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.

1 Answer 1

1

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

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

        {' ', '-', ' ',
        ' ', ' ', '|',
        ' ', '-', ' ',
        '|', ' ', ' ',
        ' ', '-', ' '}
  };
Sign up to request clarification or add additional context in comments.

6 Comments

Ah that's sad to know I can't do it my way! But this does what I want. Thanks! - Edit: Oh your edited answer does it my way, too.
Actually, the pointer method does not work. It says "a value of type char()[3] cannot be used to initialize an entity of type char ()[5][3]
Ah great! Thank you, that is 99% exactly what I wanted. Is there a way to do it without the typedef?
I get "a value of type char()[3] cannot be used to initialize an entity of type char ()[][3]"
No, that was a bad suggestion. I'm going to remove that from the answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.