malloc in C, but use multi-dimensional array syntax

后端 未结 8 1019
失恋的感觉
失恋的感觉 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:21

    In the same vein as Cogwheel's answer, here's a (somewhat dirty) trick that makes only one call to malloc():

    #define ROWS 400
    #define COLS 200
    int** array = malloc(ROWS * sizeof(int*) + ROWS * COLS * sizeof(int));
    int i;
    for (i = 0; i < ROWS; ++i)
        array[i] = (int*)(array + ROWS) + (i * COLS);
    

    This fills the first part of the buffer with pointers to each row in the immediately following, contiguous array data.

提交回复
热议问题