0

What is the difference between

int *p1[M][N]

and

int (*p2)[M][N]

Also if we define another such pointer

int (*p3)[M][N][K]

what does this represent? If anyone can explain the differences between the above three, it will be very helpful.

user2504710
  • 42
  • 1
  • 8

2 Answers2

3

int *p1[M][N] is a 2D array of pointers.

int (*p2)[M][N] is a pointer to a 2D array.

int (*p3)[M][N][K] is a pointer to a 3D array.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
0

It helps to know that you can read any C declaration using an alternating right-and-left fashion. So the direct answer to your question is:

int *p1[M][N] is an array of arrays of pointers-to-ints. int (*p2)[M][N] is a pointer to an array of arrays of ints. int (*p3)[M][N][K] is a pointer to an array of arrays of arrays of integers.

You can think of these using the standard "2D" or "3D" terminology, where a 2D array is a table with the first set of brackets indicating the row and the second set of brackets indicating the column. This is not 100% faithful to the way the computer actually works, but it's a highly effective mental model. But going back to how to decipher complicated C declarations:

You read them boustrophedonically, so first right, then left, then right, then left, and so on. Here's an example.

int * const (*p[30])(int x)

we start at the name being declared, p. We look right to get the size of p, which is 30.

So now we know p is an array of 30 something. So we look left, and we find *, so we know p is an array of 30 pointers to something. So we look right, and find the parentheses, indicating a function. Now we know p is an array of pointers to functions. We can trivially include that the parameters to these functions should be an int x.

So we've run out of things on the right, so we just keep interpreting the left elements.

p is an array of pointers to functions returning... const. There's more on the left, so keep going. p is an array of pointers to functions returning const pointers to int.

tanikaze
  • 70
  • 5