[英]fgets causing an infinite for loop in C
看来我在fgets()的实现在这里是不正确的,非常感谢您多花些时间查看我所做的事情!
这是代码
int main(int argc, const char* argv[]){
int numIntegers;
char buffer[20];
int intArray[10];
//if no argument is passed in, terminate
if (argc == 1){
printf("no argument given, terminating..\n");
return EXIT_FAILURE;
}
else{
numIntegers = atoi(argv[1]);
//we only want numbers greater than 0
if (numIntegers <= 0){
printf("# must be greater than 0\n");
return EXIT_FAILURE;
}
else{
printf("Enter %d integer values to place in array: \n", numIntegers);
for (int i = 0; i < numIntegers; i++){
fgets(buffer, numIntegers, stdin);
intArray[i] = atoi(buffer);
printf("Index is = %d \n", i);
}
}
}
//for (int i =0; i < numIntegers; i++){
// printf("Index[%d] = %d \n", i, intArray[i]);
//}
}
这是输出,用户输入除了整数以外没有其他文本的行。 请注意i的值如何重置。 仅当我给初始参数的值大于10时,才会出现此问题。无论出于何种原因,它都会将for循环变成无穷循环。
$ ./a.out 11
Enter 11 integer values to place in array:
5
Index is = 0
2
Index is = 1
1
Index is = 2
2
Index is = 3
3
Index is = 4
4
Index is = 5
123
Index is = 6
123
Index is = 7
123
Index is = 8
1
Index is = 9
2
Index is = 2
2
Index is = 3
3
Index is = 4
5
Index is = 5
1
Index is = 6
12
Index is = 7
您正在使用
fgets(buffer, numIntegers, stdin);
第二个参数应该是缓冲区的大小-在您的情况下为20。这至少是一个明显的问题...
下一个问题:您允许numIntegers
大于10-因此您将写入超出intArray
末尾的值。 也需要修复...
if(numIntegers > 10) {
printf("cannot have number greater than 10!\n");
// abort, retry, ignore...
}
实际上-这是您的代码,已消除了一些错误:请注意,对BUFSIZE
和MAXNUM
使用定义的大小只是为了避免更改MAXNUM
,而不必在多个位置进行更改...
#include <stdio.h>
#define BUFSIZE 20
#define MAXNUM 10
#define EXIT_FAILURE 0
int main(int argc, const char* argv[]){
int i, numIntegers;
char buffer[BUFSIZE];
int intArray[MAXNUM];
//if no argument is passed in, terminate
if (argc == 1){
printf("no argument given, terminating..\n");
return EXIT_FAILURE;
}
else{
numIntegers = atoi(argv[1]);
//we only want numbers greater than 0
if (numIntegers <= 0 || numIntegers > MAXNUM){
printf("# must be greater than 0 and less than %d!\n", MAXNUM);
return EXIT_FAILURE;
}
else{
printf("Enter %d integer values to place in array: \n", numIntegers);
for (i = 0; i < numIntegers; i++){
fgets(buffer, BUFSIZE, stdin);
intArray[i] = atoi(buffer);
printf("Index is = %d \n", i);
}
}
}
}
最后-您可能想知道为什么您的整数计数器似乎“重置”了? 好吧-您的intArray
是堆栈上10个整数的块; 并且当您声明循环变量i
,它占据了内存中的下一个位置(如int intArray[10];
是在到达for
循环之前最后一次声明变量的时间)-您在“索引”时碰巧到达了该位置到intArray[10]
(不允许访问的内存位置,但是无论如何您都可以访问)。 您碰巧输入了值2
因此, i
被重置为2
...
如果您在程序开始时声明了i
(就像我所做的那样,因为默认情况下我的编译器不“执行” C99-我已经老了!),问题可能会以不同的方式出现-或根本没有出现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.