dynamic allocation/deallocation of 2D & 3D arrays

后端 未结 4 2135
离开以前
离开以前 2020-12-01 05:10

I know about algorithms to allocate/deallocate a 2D array dynamically, however I\'m not too sure about the same for 3D arrays.
Using this knowledge and a bit of symmetry

4条回答
  •  失恋的感觉
    2020-12-01 05:43

    arr3d should be a triple pointer and not just an int. Otherwise looks OK:

    void deallocate3D(int*** arr3D,int l,int m)
    {
        int i,j;
    
        for(i=0;i

    arr3D is a pointer-to-pointer-to-pointer, so arr3D[i] is a pointer-to-pointer and arr3D[i][j] just a pointer. It's correct to release the lowest dimension in a loop first, and then climb up the dimensions until arr3D itself is released.

    Also it's more idiomatic to give malloc the sizeof of the pointed type implicitly. Instead of:

      arr3D[i] = (int**)malloc(m * sizeof(int*));
    

    Make it:

      arr3D[i] = (int**)malloc(m * sizeof(*arr3D[i]));
    

    And yes, such dynamically allocated multi-dimensional arrays can be accessed just as statically allocated multi-dimensional arrays.

提交回复
热议问题