dynamic allocation/deallocation of 2D & 3D arrays

后端 未结 4 2139
离开以前
离开以前 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:25

    You can see the below code:

    #include 
    #include 
    
    void main()
    {
        //  Array 3 Dimensions
        int x = 4, y = 5, z = 6;
    
        //  Array Iterators
        int i, j, k;
    
        //  Allocate 3D Array
        int *allElements = malloc(x * y * z * sizeof(int));
        int ***array3D = malloc(x * sizeof(int **));
    
        for(i = 0; i < x; i++)
        {
            array3D[i] = malloc(y * sizeof(int *));
    
            for(j = 0; j < y; j++)
            {
                array3D[i][j] = allElements + (i * y * z) + (j * z);
            }
        }
    
        //  Access array elements
        for(i = 0; i < x; i++)
        {
            printf("%d\n", i);
    
            for(j = 0; j < y; j++)
            {
                printf("\n");
    
                for(k = 0; k < z; k++)
                {
                    array3D[i][j][k] = (i * y * z) + (j * z) + k;
                    printf("\t%d", array3D[i][j][k]);
                }
            }
    
            printf("\n\n");
        }
    
        //  Deallocate 3D array
        free(allElements);
        for(i = 0; i < x; i++)
        {
            free(array3D[i]);
        }
        free (array3D);
    }
    

    For more details see this link 3d array

提交回复
热议问题