【发布时间】:2018-02-25 22:18:22
【问题描述】:
有人可以指出哪里出了问题,值 0 和 1 总是在 if 中并返回 true。 (假设数组为空)。
#include <stdio.h>
#include <stdbool.h>
#define ARRAY_SIZE 5
int getUserInput(int position){
printf("Please enter an integer for the %d position of the array\n", position);
int input;
scanf(" %d", &input);
return input;
}
bool hasValue(int value, int array[ARRAY_SIZE]){
int i;
for(i = 0; i < ARRAY_SIZE; i++){
if (value == array[i]){
printf("This value already exists in the array.\n");
return true;
}
}
return false;
}
main(){
int array[ARRAY_SIZE];
int index = 0;
while (index < ARRAY_SIZE ){
int input = getUserInput(index);
if (!hasValue(input, array)){
array[index] = input;
index++;
}
}
}
【问题讨论】:
-
没有什么“错误”。发布足够多的内容以显示
array[]的填充方式并显示hasValue()的调用方式:minimal reproducible example。 -
“数组为空”是什么意思?你的意思是“未初始化”吗?
-
您展示的代码没有什么致命的错误,但该函数仅适用于大小正好为
ARRAY_SIZE的数组。 -
没有“空”数组这样的东西。您还没有向我们展示如何定义
ARRAY_SIZE和getUserInput。如果您检查尚未初始化的值,则行为未定义,您很可能会得到垃圾值。0和1和其他任何值一样都是垃圾。 -
在
hasValue中,您应该使用i < index而不是i < ARRAY_SIZE,因为这就是您拥有的值的数量。
标签: c arrays initialization undefined