C语言 进程退出,返回值 3221225477
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24106139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Process exited with return value 3221225477
提问by kostas
i am writing this code:
我正在写这个代码:
#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;
}
and the file contains:
并且该文件包含:
2
Yiannis Ioannou 356
3
Today
10347
If
345
And then none
1542
John Smith 743
2
My story
3940
Feedback
682
END
When I try to run it, it exits me value 3221225477instead of printing the number 2..
当我尝试运行它时,它退出我的价值3221225477而不是打印数字 2..
Can anyone explain why?
谁能解释为什么?
回答by Floris
When you scan a number, you need to pass the address of the variable where you want to store the result:
当您扫描一个数字时,您需要传递要存储结果的变量的地址:
fscanf(fp,"%d",&i);
where you have
你在哪里
fscanf(fp,"%d",i);
^ missing the & sign!
Your compiler really ought to have warned you - do you enable warnings when you compile?
你的编译器真的应该警告你 - 你在编译时启用警告吗?
What is happening here is that the fscanffunction writes to the location given (in your case, it writes to whatever location is pointed toby the valueof i, instead of writing to the location of i) . This can corrupt your memory in all kinds of nasty ways - resulting, in your case, in the program "running" for considerable time before crashing.
这到底是怎么发生的是,fscanf函数写入给出的位置(在你的情况下,将其写入时的任何位置指向由价值的i,而不是写入的位置i)。这可能会以各种令人讨厌的方式破坏您的记忆 - 在您的情况下,导致程序在崩溃之前“运行”了相当长的时间。
As @Brandin pointed out, there is a further problem with your code (although it's less likely to be the source of your problem). When you attempt to open a file, you should ALWAYS check that you succeeded. You do this with something like this:
正如@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."
Alternatively, you can make things a bit prettier with:
或者,您可以通过以下方式使事情变得更漂亮:
const char *fileName = "keimeno.txt";
const char *mode = "r";
if((fp=fopen(fileName, mode))==NULL) {
printf("cannot open file %s\n", fileName);
return -1;
}
It is almost always a good idea to put "hard wired values" near the start of your program, rather than embedding them in a function call.
将“硬连接值”放在程序开头附近几乎总是一个好主意,而不是将它们嵌入到函数调用中。

