问题描述
有没有办法到malloc的大阵,而是指它与2D语法?我想是这样的:
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)];
我更preFER:
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);
我得到一个警告,从兼容的指针类型
,而code ++工程,通过ARG 1 toldyou,我已经验证了在同一地点进行访问。有没有办法做到这一点,而不使用其他功能?
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?
推荐答案
是的,你可以做到这一点,并没有像大多数其他的答案都告诉你,你不需要指针的另一个数组。你要调用仅仅是:
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
这篇关于在malloc的C,而是用多维数组语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!