C中的malloc,但使用多维数组语法

Cla*_*diu 13 c arrays malloc pointers multidimensional-array

有没有什么方法可以对大型数组进行malloc,但是用2D语法引用它?我想要的东西:

int *memory = (int *)malloc(sizeof(int)*400*200);
int MAGICVAR = ...;
MAGICVAR[20][10] = 3; //sets the (200*20 + 10)th element
Run Code Online (Sandbox Code Playgroud)


更新:这一点很重要:我只想拥有一个连续的内存块.我只是不想写一个像:

#define INDX(a,b) (a*200+b);
Run Code Online (Sandbox Code Playgroud)

然后参考我的blob:

memory[INDX(a,b)];
Run Code Online (Sandbox Code Playgroud)

我更喜欢:

memory[a][b];
Run Code Online (Sandbox Code Playgroud)


更新:我理解编译器无法按原样知道.我愿意提供额外的信息,例如:

int *MAGICVAR[][200] = memory;
Run Code Online (Sandbox Code Playgroud)

没有这样的语法吗?请注意我不仅使用固定宽度数组的原因是它太大而无法放在堆栈上.


更新:伙计们,我可以这样做:

void toldyou(char MAGICVAR[][286][5]) {
  //use MAGICVAR
}

//from another function:
  char *memory = (char *)malloc(sizeof(char)*1820*286*5);
  fool(memory);
Run Code Online (Sandbox Code Playgroud)

我收到警告,passing arg 1 of toldyou from incompatible pointer type但代码有效,我已经确认访问了相同的位置.没有使用其他功能有没有办法做到这一点?

caf*_*caf 27

是的,你可以做到这一点,不,你不需要像大多数其他答案告诉你的另一个指针数组.你想要的调用只是:

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

如果你想声明一个返回这样一个指针的函数,你可以这样做:

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

    return MAGICVAR;
}
Run Code Online (Sandbox Code Playgroud)

或者使用typedef,这使它更清晰:

typedef int (*arrayptr)[200];

arrayptr function(void)
{
    /* ... */
Run Code Online (Sandbox Code Playgroud)

  • 不公平!我先做了 (2认同)
  • @Claudiu:值得指出的是,函数参数声明中的`foo []`只是`(*foo)`的语法糖 - 它只是`[]`表示在实际变量声明中有所不同(它表示一个数组)其大小由初始化者决定). (2认同)

Tim*_*fer 19

使用指向数组的指针:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int (*arr)[10];

    arr = malloc(10*10*sizeof(int));
    for (int i = 0; i < 10; i++)
        for(int j = 0; j < 10; j++)
            arr[i][j] = i*j;

    for (int i = 0; i < 10; i++)
        for(int j = 0; j < 10; j++)
            printf("%d\n", arr[i][j]);
    free(arr);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Cog*_*eel 5

如果不需要额外的间接寻址,您可以使用指针数组。

编辑

这是 @Platinum Azure 答案的一个变体,它不会对 malloc 进行如此多的调用。除了更快的分配之外,所有元素都保证是连续的:

#define ROWS 400
#define COLS 200

int **memory = malloc(ROWS * sizeof(*memory));
int *arr = malloc(ROWS * COLS * sizeof(int));

int i;
for (i = 0; i < ROWS; ++i)
{
    memory[i] = &arr[i * COLS];
}

memory[20][10] = 3;
Run Code Online (Sandbox Code Playgroud)