在使用 GCC 编译后,我试图在 Windows 7(64 位,如果重要的话)上运行这段代码。如果我将 bufsize 声明为 int,程序会卡住并且 Windows 会通知我它已停止工作。如果我使用 #define 缓冲区大小 123 它工作正常,如果我自己用数字替换 bufsize,它工作正常。我在这里缺少什么?
int main(int argc, char* argv[]) {
char* filename = argv[1];
FILE* problem = fopen(filename, "r");
if (!problem) {
printf("File doesn't exist\n");
exit(1);
}
char* line;
while (fgets(line, bufsize, problem) != NULL) {
printf(line);
}
return 0;
}
最佳答案
line
是一个指针,但它没有指向任何地方(或者,更好的是,它还没有被初始化,它的值是不确定的和不可用的)。指向任何地方的指针不是很有用。
分配一些内存并生成line
指向那个内存。请记得在不再需要时释放内存。
line = malloc(200);
if (line == NULL) { /* something went wrong, the pointer is pointing nowhere */ }
/* ... use allocated memory ... */
free(line);
哦……还有bufsize
值应与您分配的字节数匹配。
还有 #include <stdlib.h>
因为malloc()
和 free()
那里有他们的原型(prototype)。
关于c - 奇怪的 fgets() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3746750/