文件指针不会在单独的函数中初始化(fclose 上的段错误)
kk。我需要理解生活。 当我将文件指针 fp 传递到一个新函数并在那里打开它时, fclose(fp) 会导致段错误!我发现文件指针 fp 从未打开。
main(int argc, char *argv[])
{
File *fp;
//*argv == filename
functionToOpenFile(fp,*argv);
//do stuff
fclose(fp);
}
functionToOpenFile(File *fp, char *filename)
{
fp = fopen(filename,"w");
//error handling not shown
}
我的有效解决方案是传入 fp 的地址,它是指向文件指针的指针。我不明白为什么它会改变一切
main(int argc, char *argv[])
{
File *fp;
//*argv == filename
functionToOpenFile(&fp,*argv);
//do stuff
fclose(fp);
}
functionToOpenFile(File **fp, char *filename)
{
*fp = fopen(filename,"w");
//error handling not shown
}
-AUstin
kk. i need to understand life.
when i pass fp, a File pointer, into a new function, and open it there, fclose(fp) causes a seg fault! and i discovered that the file pointer, fp, was never opened.
main(int argc, char *argv[])
{
File *fp;
//*argv == filename
functionToOpenFile(fp,*argv);
//do stuff
fclose(fp);
}
functionToOpenFile(File *fp, char *filename)
{
fp = fopen(filename,"w");
//error handling not shown
}
my solution, which works, is to pass in the address of fp, which is a pointer to a pointer to a File. i dont understand why it changes things
main(int argc, char *argv[])
{
File *fp;
//*argv == filename
functionToOpenFile(&fp,*argv);
//do stuff
fclose(fp);
}
functionToOpenFile(File **fp, char *filename)
{
*fp = fopen(filename,"w");
//error handling not shown
}
-AUstin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您发送一个指针作为参数,这意味着它将在堆栈上创建,所以您在函数中所做的更改在函数范围之外无法看到。因此,当您想要关闭文件时,您实际上是在尝试关闭之前未打开的内容。
Because you are sending a pointer as a parameter, which means it will be created on stack, so the changes you make in your function cannot be seen outside the scope of the function. So when you want to close the file, you are actually trying to close something you didnot open before.
您没有更改传递的指针,您只是更改了它的本地副本。因此,对于调用者来说,在函数结束时,很自然地看起来
functionToOpenFile
什么也没做。试试这个:有一个 C FAQ 描述了这个确切的问题。
You are not changing the passed pointer, you're only changing your local copy of it. So naturally at the end of the function for the caller it looks as if
functionToOpenFile
did nothing. Try this:There is a C FAQ describing this exact problem.
怎么样
What about