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
The compiler and runtime have no way of knowing your intended dimension capacities with only a multiplication in the malloc call.
You need to use a double pointer in order to achieve the capability of two indices. Something like this should do it:
#define ROWS 400
#define COLS 200
int **memory = malloc(ROWS * sizeof(*memory));
int i;
for (i = 0; i < ROWS; ++i)
{
memory[i] = malloc(COLS * sizeof(*memory[i]);
}
memory[20][10] = 3;
Make sure you check all your malloc return values for NULL returns, indicating memory allocation failure.