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

后端 未结 7 1345
傲寒
傲寒 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:51

    You can typedef your array (for less headake) and then do something like that:

    #include 
    #define N 10
    typedef int A[N][N];
    int main () {
      A a; // on the stack
      a[0][0]=1;
      A *b=(A*)malloc (sizeof(A)); // on the heap
      (*b)[0][0]=1;
    }
    

提交回复
热议问题