gpt4 book ai didi

c - 在 C 中打印 3d 数组中的 2d 部分(段错误)

转载 作者:行者123 更新时间:2023-11-30 18:44:24 24 4
gpt4 key购买 nike

嘿,我正在编写一个程序,该程序读取与 3D 数组的维度相对应的三个整数值(按行、列、深度的顺序),并且应该为此 3D 数组动态分配内存。然后最后打印 3D 阵列的平行于“XOY 轴”的 2D 部分。我在打印//到 XOY 轴的部分时遇到段错误(核心转储)

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


}

最佳答案

编译时出现警告:

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)

在第二个循环中将 i 更改为其他内容(即:j)

关于c - 在 C 中打印 3d 数组中的 2d 部分(段错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58270396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com