malloc in C, but use multi-dimensional array syntax

后端 未结 8 997
失恋的感觉
失恋的感觉 2020-12-04 22:59

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 MAGICV         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 23:12

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

提交回复
热议问题