How to dynamically allocate a contiguous block of memory for a 2D array

后端 未结 7 1349
傲寒
傲寒 2020-12-05 05:10

If I allocate a 2D array like this int a[N][N]; it will allocate a contiguous block of memory.

But if I try to do it dynamically like this :

<
7条回答
  •  被撕碎了的回忆
    2020-12-05 05:57

    Excuse my lack of formatting or any mistakes, but this is from a cellphone.

    I also encountered strides where I tried to use fwrite() to output using the int** variable as the src address.

    One solution was to make use of two malloc() invocations:

    #define HEIGHT 16
    #define WIDTH 16
    .
    .
    .
    //allocate
    int** data = malloc(HEIGHT*sizeof(int**));
    int* realdata = malloc(HEIGHT*WIDTH*sizeof(int));
    //manually index
    for(int i = 0;i

提交回复
热议问题