gpt4 book ai didi

c - 文件处理函数调用错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:32:46 25 4
gpt4 key购买 nike

我从 Yeshavant Kanethkar 的教科书 Let us C 中发现了一个问题。问题是您必须在以下程序中找到错误:

#include<stdio.h>
void openfile(char *, FILE **);
int main()
{
FILE *fp;
openfile( "Myfile",fp);
if(fp==NULL)
printf("Unable to open file...\n");
return 0;
}
void openfile(char *fn, FILE **f)
{
*f=fopen(fn,"r");
}

给出的答案是“没有错误”,但我不相信,因为在调用文件打开函数时我们应该通过引用调用它:

openfile("Myfile",&fp);

使用这个程序没有错误。

是我的理解正确,还是教科书正确?

最佳答案

表达

  openfile("Myfile", &fp);

代替

  openfile("Myfile", fp);

使程序完成。

openfile("Myfile", fp) 的问题在于指针类型:如果声明为 FILE *fp; 获取类型 FILE ** 来自 fp 你需要指针的地址,一元 & 可以提供帮助。

编译器可以在没有错误消息的情况下进行编译,因为 FILE *FILE ** 都是指针并且隐式转换有效,但通常会在这种情况下显示警告。

我的 Visual Studio 的警告如下所示:

Warning 1 warning C4047: 'function' : 'FILE **' differs in levels of indirection from 'FILE *' c:\users\user\documents\visual studio 2013\projects\consoleapp\source.c 10

更新:

尝试以下更新程序:

#include<stdio.h>
void openfile(char *, FILE **);

int main()
{
FILE *fp = NULL;
printf("Before:\n");
printf("value of fp = %p\n", fp);
printf("address of fp = %p\n", &fp);
openfile("Myfile", &fp);
printf("After:\n");
printf("value of fp = %p\n", fp);
printf("address of fp = %p\n", &fp);
if (fp == NULL)
printf("Unable to open file...\n");
return 0;
}

void openfile(char *fn, FILE **f)
{
printf("Inside (before):\n");
printf("value of f = %p\n", f);
printf("value of *f = %p\n", *f);
*f = fopen(fn, "r");
printf("Inside (after):\n");
printf("value of f = %p\n", f);
printf("value of *f = %p\n", *f);
}

如果你的程序可以打开文件,你会看到类似的东西

Before:
value of fp = 00000000
address of fp = 0019F9B0
Inside (before):
value of f = 0019F9B0
value of *f = 00000000
Inside (after):
value of f = 0019F9B0
value of *f = 580E7350
After:
value of fp = 580E7350
address of fp = 0019F9B0

这里我们看到了地址,fp 的值在调用 openfile 后发生了变化

关于c - 文件处理函数调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41119699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com