FILE指针在C中作为函数参数不同

时间:2015-10-09 15:23:16

标签: pass-by-value member-function-pointers ansi-c

在下面的代码中,我创建了一个char指针和一个FILE指针,并尝试将两者都传递给函数"当然值为#34;。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void move(char *s){
    ++s;
}
void moveF(FILE *f){
    getc(f);
}
int main(){
    char *s = malloc(64);
    strcpy(s,"123456");
    puts(s);
    move(s);
    puts(s);

    //~~~~~~~~~~
    FILE *f = fopen("file1","r");
    printf("%d\n",(int)ftell(f));
    moveF(f);
    printf("%d\n",(int)ftell(f));
}

我知道按值传递意味着该参数是调用函数中原始变量的副本,这就是为什么你可以注意到在传递了char指针之后,它在main函数中的值根本没有改变,但奇怪的是传递一个FILE指针并改变参数的值导致改变main函数内变量的值。

有人可以解释一下这种行为。 谢谢。

1 个答案:

答案 0 :(得分:0)

将指针传递给对象与通过引用传递对象相同。因此,您通过引用传递FILE结构。任一函数中的指针都指向内存中的同一个对象,因此可以修改对象并查看其他对象的更改。