Reputation: 4378
As I see it int *x[n][m]
declares x
to be a 2-d array of pointers to integers, so allocating memory should be as easy as x[i][j] = new int
and as expected it works fine. Now if I change the declaration to:
int (*x)[n][m]
x[i][j] = new int
no longer works and results in a compilation error.
x = (int(*)[n][m]) malloc (sizeof(int[n][m]))
however compiles. From the few tests I ran, after the memory allocation, the different declaration/allocation combination doesn't seem to effect the values stored in the variable. Am I missing something? So my question is, **Is there a difference between int *x[n][m] and int (x)[m][n]. How is int (x)[n][m] stored in memory?
Upvotes: 13
Views: 6028
Reputation: 5039
Good site to decode C-declaration names. Taking your examples (and substituting n=1
and m=2
) we see:
int *x[1][2]
Translates to:
declare x as array 1 of array 2 of pointer to int
Whereas
int (*x)[1][2]
Translates to:
declare x as pointer to array 1 of array 2 of int
Upvotes: 1
Reputation: 10868
As you can easily discover:
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.
Upvotes: 4
Reputation: 55395
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
Upvotes: 21