The following snippet declares a 2-D array of 4 X 10 using malloc function
/* Declare a pointer to an array that has 10
ints in each row. */
int (*p)[10];
register int i, j;
/* allocate memory to hold a 4 x 10 array */
p = malloc(40*sizeof(int));
But I do not understand how does p become a 2-D array. Initially p is declared to be an array of pointers that point to int. What happens after the call to malloc ? I am unable understand this.
In C, pointers and arrays are not the same, despite looking very similar. Here
pis of type “pointer to array of 10 ints”. You’re using it as a “pointer to array of 4 arrays of 10 ints”, which is a single block of memory (the only pointer is the outermost pointer). It’s basically a dynamically allocatedint[4][10].The trick to reading these definitions is to realize that they’re written the same way you use the item. If you have:
The array subscript is applied first, then the pointer dereference. So it’s an array of pointers if you define
int *x[10]. If you use parenthesis to override normal precedence, you can get the pointer dereference to happen first, so you have a pointer to an array.Confusing? It gets worse. In function arguments, the outermost array of a function parameter is converted into a pointer.
Further, arrays are converted to pointers when you use them.
This means that you can allocate memory for an array of arrays, then let that implicitly convert to a pointer to an array, which you in turn use as if it were an array of arrays!
Anyway, this is all very confusing so please do not ever use this in production code – at least, not without a clarifying typedef: