0

So I have a pointer to a 2D array like so:

int board[3][5] = { 3, 5, 2, 2, 1, 3, 4, 34, 2, 2, 3, 4, 3, 223, 923 };
int* ptr[sizeof(board[0]) / sizeof(board[0][0])] = board;

I'm trying to follow this example. But for some reason I'm getting the error:

IntelliSense: initialization with '{...}' expected for aggregate object

Any idea what the problem is?

Community
  • 1
  • 1
Richard
  • 5,840
  • 36
  • 123
  • 208
  • 1
    This question has an answer [here](http://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation) – Kevin Jan 31 '14 at 09:24

3 Answers3

1

Assign pointer to the first element of the array like below

int (*ptr)[5] = board;

Note: Column size [5] in the pointer declaration should be equal to the original 2 dimension array column size [5]. Declaring row size [3] is optional.

int main() {

    int board[3][5] = { 3, 5, 2, 2, 1, 3, 4, 34, 2, 2, 3, 4, 3, 223, 923 };

    /*
    // 3 Rows 5 Columns Matrix
       int board[3][5] = { {3, 5, 2, 2, 1 },
                           {3, 4, 34, 2, 2 },
                           {3, 4, 3, 223, 923}
                         };
   */

   // Assign pointer to the first element of the array
   int (*ptr)[5] = board;

   for(int i=0; i< (3*5); i++) {
       std::cout<<(*ptr)[i]<<std::endl;
    }

   return 0;
}
SridharKritha
  • 8,481
  • 2
  • 52
  • 43
0

A 2D array is not the same as an array of pointers. You cannot directly convert one to the other.

user253751
  • 57,427
  • 7
  • 48
  • 90
0

I just needed to put () around the *ptr. I have no idea how this fixes it but now I can do ptr[1][2].

Richard
  • 5,840
  • 36
  • 123
  • 208