Is there any way to malloc a large array, but refer to it with 2D syntax? I want something like:
int *memory = (int *)malloc(sizeof(int)*400*200);
int MAGICV
#define ROWS 400
#define index_array_2d(a,i,j) (a)[(i)*ROWS + (j)]
...
index_array_2d( memory, 20, 10 ) = -1;
int x = index_array_2d( memory, 20, 10 );
Arrays and pointers look very much the same, but the compiler treats them very differently. Let's see what needs to be done for an array indexing and de-referencing a pointer with offset:
Say we declared a static array (array on the stack is just a bit more complicated, fixed offset from a register, but essentially the same):
static int array[10];
And a pointer:
static int* pointer;
We then de-deference each as follows:
x = array[i];
x = pointer[i];
The thing to note is that address of the beginning of array, as well as, address of pointer (not its contents) are fixed at link/load time. Compiler then does the following:
array de-reference:
i,array, i.e. its fixed address, to form target memory address,pointer de-reference:
i,pointer, i.e. the contents at its address,Same happens for 2D array with additional steps of loading the second index and multiplying it by the row size (which is a constant). All this is decided at compile time, and there's no way of substituting one for the other at run-time.
@caf here has the right solution. There's a legal way within the language to index a pointer as two-dimentional array after all.