Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

pointers - 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:

memory[INDX(a,b)];

I'd much prefer:

memory[a][b];


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]) {
  //use MAGICVAR
}

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

If you wish to declare a function returning such a pointer, you can either do it like this:

int (*func(void))[200]
{
    int (*MAGICVAR)[200] = malloc(400 * sizeof *MAGICVAR);
    MAGICVAR[20][10] = 3;

    return MAGICVAR;
}

Or use a typedef, which makes it a bit clearer:

typedef int (*arrayptr)[200];

arrayptr function(void)
{
    /* ... */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...