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

后端 未结 7 1326
傲寒
傲寒 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:44

    The best way is to allocate a pointer to an array,

    int (*a)[cols] = malloc(rows * sizeof *a);
    if (a == NULL) {
        // alloc failure, handle or exit
    }
    
    for(int i = 0; i < rows; ++i) {
        for(int j = 0; j < cols; ++j) {
            a[i][j] = i+j;
        }
    }
    

    If the compiler doesn't support variable length arrays, that only works if cols is a constant expression (but then you should upgrade your compiler anyway).

提交回复
热议问题