【发布时间】:2020-03-23 10:45:31
【问题描述】:
注意:我已编辑我的代码以提供清晰且最少的步骤来重现错误。 我使用 C99 标准编写了以下代码:
#include <stdio.h>
#include <stdbool.h>
bool FillMatrix(int MatrixSize, int Matrix[][10])
{
int CellValue=0;
for (int i=0;i<MatrixSize;i++)
{
for (int j = 0; j < MatrixSize; j++)
{
if (scanf("%d",&CellValue) == 0)//Check if User provided un-integer value
{
printf("Error\n");
return false;//Her's the problem
}
else
{
Matrix[i][j] = CellValue;
}
}
}
return true;
}
int main()
{
int MatrixSize=0;
scanf("%d",&MatrixSize);
int FirstMatrix[10][10],SecondMatrix[10][10];
printf("First:\n");
if (!FillMatrix(MatrixSize,FirstMatrix)) return 0;
printf("Second:\n");
if (!FillMatrix(MatrixSize,SecondMatrix)) return 0;
printf("Hello");
return 0;
}
当我提供1 作为第一个输入,然后提供4.5 时,我可以在屏幕上看到Error,但也可以看到Second:
我的代码有什么问题?
在打印 Second 之前,我要求验证 FillMatrix(...) 没有返回 false,但它仍然会被打印出来!
【问题讨论】:
-
旁白:
if (scanf("%d",&CellValue) == 0)应该是if (scanf("%d",&CellValue) != 1),因为您将无法检测到何时返回EOF。但是您应该发布 Minimal Reproducible Example 来表明问题,因为任何事情都可能是负责任的。 -
出于好奇,
print_invalid_input是做什么的? -
@edtheprogrammerguy 我已经完全重新排列了我的代码,使其更加清晰和简洁。你能看一下吗?
-
请注意Minimal Reproducible Example应该是一个完整的程序,可以在一次操作中复制粘贴,然后编译(没有警告)并运行!
-
重新排序函数时,无法重现。可能您的编译器不够严格,无法拒绝编译,并且传递的数组参数被错误地使用,从而破坏了某些东西。在默认情况下,它可能传递了一个被截断为 32 位
int而不是 64 位指针的指针
标签: c function return main c99