#include <stdio.h>
int main(void){
FILE *fp = fopen("loop.txt" , "r");
printf("%p\n",fp);
}
output :
Run 1 : 0x101d010
Run 2 : 0x13f9010
Run 3 : 0xeaf010
Why is the output different every time ?
#include <stdio.h>
int main(void){
FILE *fp = fopen("loop.txt" , "r");
printf("%p\n",fp);
}
output :
Run 1 : 0x101d010
Run 2 : 0x13f9010
Run 3 : 0xeaf010
Why is the output different every time ?
The fopen() function call returns a pointer to a FILE structure that 'describes' the file, in terms of what the operating system needs in order to access that file on disk. That FILE structure will be located somewhere in memory (allocated at run-time); the actual location (address) of that memory block will vary between different runs of the program - which is exactly why you need to keep track of it in your fp (pointer) variable.
All other calls to library functions (such as fwrite(), fread() and fclose()), which access that file, will need that fp variable as a parameter; this indicates to the functions (and to the system) which file object you are working with.
To give an authoritative and detailed explanation about why your program receives a different address in the file pointer, each time you run it, would require equally detailed and authoritative knowledge of your system's implementation of the fopen() call (and related I/O support code) – and that is knowledge that I don't have.
However, here are two possible explanations:
Each time you call fopen(), the system allocates space for the required FILE structure by calling malloc(sizeof(FILE)); this will return the address of the first available chunk of system memory of sufficient size, which will clearly vary between runs, depending on what other programs and/or services are using the system's memory pool.
The I/O subsystem has a fixed, internal table of FILE structures, each with its (fixed) starting address; when you call fopen(), the system assigns the first available table entry to your opened file and the function returns the address of that. But this can also vary between runs, depending on what other programs/services are using entries in that table.
If I had to make a guess (and that's all it would be), the large differences between the addresses you show in your example would tend to make me favour the first possibility. But there are numerous other ways your system could handle the task.