问题描述
有什么办法可以 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);
然后像这样引用我的 blob:
and then refer to my blob like:
memory[INDX(a,b)];
我更喜欢:
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);
我收到一个警告,从不兼容的指针类型传递了告诉你的 arg 1
,但代码有效,我已经验证访问了相同的位置.有没有办法在不使用其他功能的情况下做到这一点?
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
如果你想声明一个返回这样一个指针的函数,你可以这样做:
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;
}
或者使用 typedef,这样会更清楚一点:
Or use a typedef, which makes it a bit clearer:
typedef int (*arrayptr)[200];
arrayptr function(void)
{
/* ... */
这篇关于C 中的 malloc,但使用多维数组语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!