据我所知,将指针传递给函数本质上是将指针的副本传递给 C 中的函数。我有一个 FILE
指针,我将它传递给函数 func( )
,func()
从文件中读取一行,然后当我们返回到main()
。我使用相同的 FILE
指针从文件中读取了另一行。
但是,虽然我想我会在调用 func()
之前准确地读取该行,但实际上我在 func()
之后读取了下一行读过。 你能解释一下为什么 FILE
指针会这样吗?
这是我的代码:
#include <stdio.h>
#define STR_LEN 22
void func(FILE *fd);
int main() {
FILE *fd;
char mainString[STR_LEN];
if (!(fd = fopen("inpuFile", "r"))) {
printf("Couldn't open file\n");
fprintf(stderr, "Couldn't open file\n");
}
func(fd);
fgets(mainString, STR_LEN, fd);
printf("mainString = %s\n", mainString);
fclose(fd);
return 0;
}
void func(FILE *fd) {
char funcString[STR_LEN];
fgets(funcString,STR_LEN, fd);
printf("funcString = %s\n", funcString);
}
最佳答案
However, while I would imagine that I'd read the line exactly from before func was called ...
我无法想象你为什么会这样想。如果 FILE*
引用的网络连接根本没有重播能力,而读取是消耗品。该行将存储在哪里以便您可以再次阅读它?绝对没有地方放它。
我不仅不会想象,这有点疯狂。
As far as I understand passing a pointer to a function essentially passes the copy of the pointer to the function in C.
正确。但是指针的副本指向同一个对象。如果我指着一辆车,而你复制我,那么你指的是我所指的那辆车,也是唯一一辆。
关于c - 为什么 FILE 指针在传递给函数后在 C 中返回 main 时会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42364762/