C 进程已退出,返回值为322225477
我在写这段代码:C 进程已退出,返回值为322225477,c,C,我在写这段代码: #include<stdio.h> #include<stdlib.h> int main() { FILE *fp; int i; fp = fopen("keimeno.txt","r"); fscanf(fp,"%d",i); printf("%d\n",i); fclose(fp); return 0; } 当我尝试运行它时,它会退出我的值322225477,而不是打印数字2 有人能解释一下原因吗?当你扫描一个数字时,你需要将变量的地址
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
int i;
fp = fopen("keimeno.txt","r");
fscanf(fp,"%d",i);
printf("%d\n",i);
fclose(fp);
return 0;
}
当我尝试运行它时,它会退出我的值322225477
,而不是打印数字2
有人能解释一下原因吗?当你扫描一个数字时,你需要将变量的地址传递给你想要存储结果的地方:
fscanf(fp,"%d",&i);
你在哪里
fscanf(fp,"%d",i);
^ missing the & sign!
您的编译器真的应该警告您-您在编译时启用了警告吗
这里发生的情况是,fscanf
函数写入给定的位置(在您的情况下,它写入i
的值指向的任何位置,而不是写入i
的位置)。这会以各种令人讨厌的方式损坏您的内存——在您的情况下,导致程序在崩溃之前“运行”相当长的时间
正如@Brandin指出的,您的代码还有一个问题(尽管它不太可能是问题的根源)。尝试打开文件时,应始终检查是否成功。你可以这样做:
#include <assert.h>
// at the top of the program
// attempt to open the file:
fp = fopen("keimeno.txt","r");
// and check whether you succeeded:
assert(fp != NULL); // this says "check fp is not NULL. Otherwise, quit."
将“硬接线值”放在程序开始处,而不是将其嵌入函数调用中,这几乎总是一个好主意。除此之外,OP还应在fopen之后检查返回值。假设它总是有效的,也很容易导致未定义的行为。@Brandin你是对的-但通常带有空指针的
fscanf
会给出更可预测的错误消息。我将更新我的答案以包含此信息。谢谢,它起作用了…这不是我的代码…在我的代码中,我正在检查文件是否可以打开使用assert进行成功测试如果您在发布模式下编译(例如使用NDEBUG
定义),则使用进行成功测试将不起作用。正确的方法是使用if语句,如示例所示。@Brandin-我假设任何硬连接到当前目录的文件路径的人都是在调试模式下工作,而不是在发布模式下工作。但你的观点(再次)是正确的——谢谢。您认为有必要从答案中删除assert
方法吗?仅供参考:十六进制的返回值为0xC0000005或状态\u访问\u冲突。
#include <assert.h>
// at the top of the program
// attempt to open the file:
fp = fopen("keimeno.txt","r");
// and check whether you succeeded:
assert(fp != NULL); // this says "check fp is not NULL. Otherwise, quit."
const char *fileName = "keimeno.txt";
const char *mode = "r";
if((fp=fopen(fileName, mode))==NULL) {
printf("cannot open file %s\n", fileName);
return -1;
}