如果我输入以下代码,下面的代码将给出错误的答案:
1st Matrix
1 2 3
4 5 6
7 8 9
2nd Matrix
2 2 2
2 2 2
2 2 2
它给了我这个矩阵和输出:
9 10 11
9 10 11
9 10 11
这显然是错误的!我似乎找不到原因?
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int r,c;
int ir,ic;
int matrix1[r][c];
int matrix2[r][c];
int finalmatrix[r][c];
printf("Insert number of rows of the matrixes (max 10): ");
scanf("%d", &r);
printf("Insert number of columns of the matrixes (max 10): ");
scanf("%d", &c);
while(r!=c)
{
printf("The number of rows and columns are not equal, retry:\n");
printf("Insert number of rows of the Matrix (max 10): ");
scanf("%d", &r);
printf("Insert number of columns of the Matrix (max 10): ");
scanf("%d", &c);
}
for(ir=1; ir<=r; ir++)
{
for(ic=1; ic<=c; ic++)
{
printf("Insert element row %d and column %d of the first matrix: ", ir, ic);
scanf("%d", &matrix1[ir][ic]);
}
}
for(ir=1; ir<=r; ir++)
{
for(ic=1; ic<=c; ic++)
{
printf("Insert element row %d and column %d of the second matrix: ", ir, ic);
scanf("%d", &matrix2[ir][ic]);
}
}
for(ir=1; ir<=r; ir++)
{
for(ic=1; ic<=c; ic++)
{
finalmatrix[ir][ic]=matrix1[ir][ic]+matrix2[ir][ic];
}
}
printf("The sum Matrix is:\n");
for(ir=1; ir<=r; ir++)
{
for(ic=1; ic<=c; ic++)
{
printf("%d ", finalmatrix[ir][ic]);
}
printf("\n");
}
return 0;
}
最佳答案
您的代码在声明 VLA 之前无法初始化变量 r
和 c
。您无法知道这些数组的大小,或者 r
和 c
是否为正值!我很惊讶这段代码竟然还能运行。我运行了您发布的代码,并收到了此运行时错误:
runtime error: variable length array bound evaluates to non-positive value -1208010352
我进行了以下更改,并且代码有效:
int r,c;
int ir,ic;
printf("Insert number of rows of the matrixes (max 10): ");
scanf("%d", &r);
printf("Insert number of columns of the matrixes (max 10): ");
scanf("%d", &c);
int matrix1[r][c];
int matrix2[r][c];
int finalmatrix[r][c];
示例的输出:
The sum Matrix is:
3 4 5
6 7 8
9 10 11
根据标准中关于数组声明符的部分:
the [ and ] may delimit an expression.... If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. (ISO/IEC 9899:1999 6.7.5.2/1)
If the size is an expression that is not an integer constant expression... each time it is evaluated it shall have a value greater than zero. (ISO/IEC 9899:1999 6.7.5.2/5)
因此,r
或 c
的负值很可能会导致未定义的行为,这意味着任何事情都可能发生!当我运行代码时,出现运行时错误。您运行相同的代码,却得到了不同的结果。该行为未定义,因此不知道会发生什么。
关于c - 为什么这个矩阵加法代码给出了错误的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40704844/