Today a colleague at work showed me a way of declaring a 2D array in such a way that I can allocate it linearly but still use 2D square bracket ([][]
) notation to access elements.
For example:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 2
int main () {
int (*a)[SIZE][SIZE] = malloc (sizeof (int) * SIZE * SIZE);
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
(*a)[i][j] = 0;
}
}
(*a)[0][1] = 100;
/* should yield:
* 0
* 100
* 0
* 0
*/
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf ("%d\n", (*a)[i][j]);
}
}
free (a);
return EXIT_SUCCESS;
}
This is in contrast to computing the index and then perform pointer arthimetic (e.g. *(a + (x * SIZE + y))
or more tersly a[x * SIZE + y]
) to access an element.
The critical part is the shape declaration of the pointer x
(e.g. (*x)[][]
), which seems to encode this information as a type for the value that x
points to.
Beyond this though I do not understand how this works. What does this notation exactly doing? Is it syntactic sugar? It looks symilar to dynamic stack allocation for arrays (see Array size at run time without dynamic allocation is allowed? as one example of this), but clearly this allocation is happening on the heap.
I've looked for more information about this notation/declaration of the pointer but can't find much other than the term element type coming up - but I'm not certain that this is related.
EDIT #1:
I should have mentioned this question is in the context of using the heap, and not the stack. I'm aware of stack based dynamic allocation of arrays, but the work I'm doing specifically looks at dynamic memory allocations.