Reputation: 5093
I'd like to ask why is it possible to change the pointer value of file in C function without passing reference to it, what I mean is:
void fun(FILE *f)
{
fclose(f);
f = fopen("newfile", "r");
}
int main(void)
{
FILE *old = fopen("file", "r");
char *msg = (char*)malloc(sizeof(char) * 100);
fun(old);
fscanf(old, "%s", msg);
printf("%s", msg);
free(msg);
return 0;
}
Can anyone explain it to me? I was thought that pointers are being copied so I expected to get an error about closed file. Surprisingly I didn't get it.
Upvotes: 0
Views: 2455
Reputation: 409442
Arguments in C is passed by value, and that means they are copied. So the functions never have the original values, just copies, and modifying a copy will of course not modify the original.
You can emulate pass by reference by using pointers, and in the case of passing a pointer by reference you of course have to pass a pointer to the pointer (by using the address-of operator &
).
void fun(FILE **f)
{
fclose(*f);
*f = fopen("newfile", "r");
}
...
fun(&old);
Upvotes: 3