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

后端 未结 7 1342
傲寒
傲寒 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:01

    Say you want to dynamically allocate a 2-dimensional integer array of ROWS rows and COLS columns. Then you can first allocate a continuous chunk of ROWS * COLS integers and then manually split it into ROWS rows. Without syntactic sugar, this reads

    int *mem = malloc(ROWS * COLS * sizeof(int));
    int **A = malloc(ROWS * sizeof(int*));
    for(int i = 0; i < ROWS; i++) 
       A[i] = mem + COLS*i;
    // use A[i][j]
    

    and can be done more efficiently by avoiding the multiplication,

    int *mem = malloc(ROWS * COLS * sizeof(int));
    int **A = malloc(ROWS * sizeof(int*));
    A[0] = mem;
    for(int i = 1; i < ROWS; i++) 
       A[i] = A[i-1] + COLS;
    // use A[i][j]
    

    Finally, one could give up the extra pointer altogether,

    int **A = malloc(ROWS * sizeof(int*));
    A[0] = malloc(ROWS * COLS * sizeof(int));
    for(int i = 1; i < ROWS; i++) 
       A[i] = A[i-1] + COLS;
    // use A[i][j]
    

    but there's an important GOTCHA! You would have to be careful to first deallocate A[0] and then A,

    free(A[0]);
    free(A);              // if this were done first, then A[0] would be invalidated
    

    The same idea can be extended to 3- or higher-dimensional arrays, although the code will get messy.

提交回复
热议问题