简体   繁体   English

在 C 中打印 3d arrays 中的二维部分(分段错误)

[英]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.嘿,我正在做一个程序,它读取三个 integer 值对应于 3D 数组的维度(按行、列、深度的顺序),并且应该为这个 3D 数组动态分配 memory。 then finally printing the 2D-sections of the 3D-array which are parallel to the “XOY axis”.然后最后打印与“XOY 轴”平行的 3D 阵列的 2D 截面。 I am getting Segmentation fault (core dumped) in the printing of the the sections // to XOY axis我在打印部分//到 XOY 轴时遇到Segmentation fault (core dumped)

#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)警告:阴影声明在这里 [-Wshadow] for (int i = 0; i < dim1; ++i)

Change i to something else (ie: j ) in the second loop在第二个循环中将i更改为其他内容(即: j

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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