[英]C not printing 2D dynamic array content
I am trying to make a 2D dynamic array that calculates the derteminant of 4 or 9 numbers.我正在尝试制作一个计算 4 或 9 个数字的行列式的 2D 动态数组。
While using pointers and a dynamic array worked flawlessly in a 1D array, I can't wrap my head around what I have to do to make it owrk in 2D.虽然在 1D 数组中使用指针和动态数组可以完美地工作,但我无法理解我必须做什么才能使其在 2D 中运行。 So far, the program compiles properly and receives input.
到目前为止,程序正确编译并接收输入。 However, it does not print anything.
但是,它不会打印任何内容。 I even tried printing a single cell content.
我什至尝试打印单个单元格内容。 Nothing.
没有。
Here is the code:这是代码:
#include <stdio.h>
#include <stdlib.h>
int size; int i; int j; int **arDet; int a; int b; int c; int d; int e; int f; int g; int h;
int input()
{
do
{
scanf("%d", &size);
}while(size > 3 || size < 2);
arDet = (int**)malloc(sizeof(int)*size);
for(i = 0 ; i < size; i++)
{
for(j = 0 ; j < size; j++)
{
scanf("%d", &arDet[i][j]);
}
}
}
int main()
{
input();
if(size == 2)
{
printf("%d\n", arDet[0][0]*arDet[1][1] - arDet[0][1]*arDet[1][0]);
return 0;
}else if(size == 3)
{
// printf("%d", arDet[0]*(arDet[4]*arDet[8] - arDet[7]*arDet[5]) - arDet[1]*(arDet[3]*arDet[8] - arDet[5]*arDet[6]) + arDet[2]*(arDet[3]*arDet[7] - arDet[6]*arDet[4]));
return 0;
}else
{
return -1;
}
}
arDet
is wrong. arDet
的大小计算是错误的。 The elements of arDet
are int*
. arDet
的元素是int*
。 int
(4 bytes for example) has shorter size than int*
(8 bytes for example) in some environments and your code will cause trouble in such environments.int
(例如 4 个字节)的大小比int*
(例如 8 个字节)更短,并且您的代码在此类环境中会导致问题。malloc()
in C is discouraged . malloc()
结果。 arDet = malloc(sizeof(arDet[0])*size); /* fix size calculation */
for(i = 0 ; i < size; i++)
{
arDet[i] = malloc(sizeof(arDet[i][0]) * size); /* add this */
for(j = 0 ; j < size; j++)
{
scanf("%d", &arDet[i][j]);
}
}
Also note that the commented line另请注意,注释行
// printf("%d", arDet[0]*(arDet[4]*arDet[8] - arDet[7]*arDet[5]) - arDet[1]*(arDet[3]*arDet[8] - arDet[5]*arDet[6]) + arDet[2]*(arDet[3]*arDet[7] - arDet[6]*arDet[4]));
doesn't make sense because C doesn't support multiplying two pointers and indice above 2 is out-of-range when size
is 3.没有意义,因为 C 不支持将两个指针相乘,并且当
size
为 3 时,大于 2 的索引超出范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.