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

后端 未结 7 1270
傲寒
傲寒 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 06:03

    In fact, n-dimensional arrays (allocated on the stack) are really just 1-dimension vectors. The multiple indexing is just syntactic sugar. But you can write an accessor function to emulate something like what you want:

    int index_array(int *arr, size_t width, int x, int y)
    {
        return arr[x * width + y];
    }
    
    const size_t width = 3;
    const size_t height = 2;
    int *arr = malloc(width * height * sizeof(*arr));
    
    // ... fill it with values, then access it:
    
    int arr_1_1 = index_array(arr, width, 1, 1);
    

    However, if you have C99 support, then declaring a pointer to an array is possible, and you can even use the syntactic sugar:

    int (*arr)[width] = malloc(sizeof((*arr) * height);
    arr[x][y] = 42;
    
    0 讨论(0)
提交回复
热议问题