-1

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");
    }


}

John C.
  • 405
  • 5
  • 19
  • Voting to close as a simple typo. – Sander De Dycker Oct 07 '19 at 13:23
  • Unrelated to the problem, you might want to use 3D arrays instead. See [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays). – Lundin Oct 07 '19 at 13:25
  • And as an aside, [do not cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – lurker Oct 07 '19 at 13:27

1 Answers1

2

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 (i.e.: j) in the second loop

David Ranieri
  • 39,972
  • 7
  • 52
  • 94