What is the difference between int* x[n][m] and int (*x) [n][m]?
int *a[n][m]
is a two dimensional array of pointers to int
.
int (*p)[n][m]
is a pointer to a two dimensional array of int
s (it is the type you get by taking the address of int[n][m]
).
In both cases, n
and m
need to be compile time constants, otherwise the declarations are not legal in C++ (but are in C). Your compiler might have an extension to allow it, though.
First one can be used to simulate a three dimensional array. I say simulate, because it would not be a proper array with contiguous storage and the types are different in the first place. In each of the elements of a
you can store the address to the first element of an array of integers. Each could have a different size and be allocated dynamically. You can store a pointer to a single (possibly stack allocated) integer, too.
int i = 0;
int a1[2] = {};
int* a2[2][2];
a2[0][0] = a1; // array to pointer decay here
a2[0][1] = new int[42];
a2[1][0] = new int[84];
a2[1][1] = &i;
p
can point to a single 2d array or an array thereof:
int arr[2][3];
int (*p1)[2][3] = &arr; // arr decays to int(*)[3], so we need to take the address
int (*p2)[2][3] = new int[42][2][3]; // allocate 42 arrays dynamically
As you can easily discover:
- int *x[n][m] is a two dimensional array of pointers to int.
- int (*x)[n][m] is a pointer to a two dimensional array of ints.
The answer to your question is that the first is an array so the memory is 'inline' - it might be static, automatic (on the stack) or on the heap, depending on where you define it.
The second is a pointer to an array and the pointer must be initialised before what it points to is used. Most likely the memory will be allocated on the heap, but it's also possible that it might be a static or auto array defined elsewhere. If you access members of the array before initialising the pointer, you get Undefined Behaviour.