Claudiu Claudiu - 1 year ago 60
C Question

malloc in C, but use multi-dimensional array syntax

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 MAGICVAR = ...;
MAGICVAR[20][10] = 3; //sets the (200*20 + 10)th element

UPDATE: This was important to mention: I just want to have one contiguous block of memory. I just don't want to write a macro like:

#define INDX(a,b) (a*200+b);

and then refer to my blob like:


I'd much prefer:


UPDATE: I understand the compiler has no way of knowing as-is. I'd be willing to supply extra information, something like:

int *MAGICVAR[][200] = memory;

Does no syntax like this exist? Note the reason I don't just use a fixed width array is that it is too big to place on the stack.

UPDATE: OK guys, I can do this:

void toldyou(char MAGICVAR[][286][5]) {

//from another function:
char *memory = (char *)malloc(sizeof(char)*1820*286*5);

I get a warning,
passing arg 1 of toldyou from incompatible pointer type
, but the code works, and I've verified that the same locations are accessed. Is there any way to do this without using another function?

caf caf
Answer Source

Yes, you can do this, and no, you don't need another array of pointers like most of the other answers are telling you. The invocation you want is just:

int (*MAGICVAR)[200] = malloc(400 * sizeof *MAGICVAR);
MAGICVAR[20][10] = 3; // sets the (200*20 + 10)th element