且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-23 16:10:36

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

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)
{
    /* ... */