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

后端 未结 7 1305
傲寒
傲寒 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:59

    If your array dimensions are known at compile time:

    #define ROWS ...
    #define COLS ...
    
    int (*arr)[COLS] = malloc(sizeof *arr * ROWS);
    if (arr) 
    {
      // do stuff with arr[i][j]
      free(arr);
    }
    

    If your array dimensions are not known at compile time, and you are using a C99 compiler or a C2011 compiler that supports variable length arrays:

    size_t rows, cols;
    // assign rows and cols
    int (*arr)[cols] = malloc(sizeof *arr * rows);
    if (arr)
    {
      // do stuff with arr[i][j]
      free(arr);
    }
    

    If your array dimensions are not known at compile time, and you are not using a C99 compiler or a C2011 compiler that supports variable-length arrays:

    size_t rows, cols;
    // assign rows and cols
    int *arr = malloc(sizeof *arr * rows * cols);
    {
      // do stuff with arr[i * rows + j]
      free(arr);
    }
    

提交回复
热议问题