简体   繁体   中英

Printing 2d sections in 3d arrays in C ( segmentation fault )

Hey I am doing a program that read three integer values corresponding to the dimensions of a 3D-array(in the order of rows, columns, depth) and should dynamically allocate the memory for this 3D-array. then finally printing the 2D-sections of the 3D-array which are parallel to the “XOY axis”. I am getting Segmentation fault (core dumped) in the printing of the the sections // to XOY axis

#include <stdio.h>
#include <stdlib.h>

void read_matrices(int dim1, int dim2, int dim3, int ***A);
void XOY(int dim1, int dim2, int dim3, int ***A);



int main(int argc, char const *argv[])
{
    /* code */

    int dim1, dim2, dim3;
    scanf("%d%d%d", &dim1, &dim2, &dim3);
    int i,j;
    int *** array = (int ***)malloc(dim1*sizeof(int**));

        for (i = 0; i< dim1; i++) {

        array[i] = (int **) malloc(dim2*sizeof(int *));

            for (j = 0; j < dim2; j++) {

              array[i][j] = (int *)malloc(dim3*sizeof(int));
            }

        }



    read_matrices(dim1,dim2,dim3, array);  
    XOY(dim1,dim2,dim3, array); 
    return 0;
}

void read_matrices(int dim1, int dim2, int dim3, int ***A)
{
  //getting input of the arrays A & B

  int a,b,c;
  for (a = 0; a < dim1; ++a)
  {
    for (b = 0; b < dim2; ++b)
    {
        for (c = 0; c < dim3; ++c)
        {
          scanf("%d", &A[a][b][c]);

        }
    }
  }

}

void XOY(int dim1, int dim2, int dim3, int ***A)
{

printf("Section 1:\n");
    for (int i = 0; i < dim1; ++i)
    {
        for (int i = 0; i < dim2; ++i)
        {
            printf("%d ", A[i][i][0]);
        }
        printf("\n");
    }



printf("Section 2:\n");
    for (int i = 0; i < dim2; ++i)
    {
        for (int i = 0; i < dim3; ++i)
        {
            /* code */
            printf("%d ", A[0][i][i] );

        }
        printf("\n");
    }

printf("Section 3:\n");
    for (int i = 0; i < dim1; ++i)
    {
        for (int i = 0; i < dim3; ++i)
        {
            /* code */
            printf("%d ", A[i][0][i] );

        }
        printf("\n");
    }


}

Compile with warnings:

for (int i = 0; i < dim1; ++i)
{
    for (int i = 0; i < dim2; ++i)

warning: shadowed declaration is here [-Wshadow] for (int i = 0; i < dim1; ++i)

Change i to something else (ie: j ) in the second loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM