In the following program, file_ptr is NULL, yet it is being initialized properly. Why?
#include <stdio.h>
#include <stdlib.h>
void Fopen(const char * restrict filePath, const char * restrict mode, FILE * restrict filePtr);
int main(int argc, char ** argv)
{
FILE * file_ptr = NULL;
Fopen("dummy.dat", "r", file_ptr);
printf("File pointer is %p\n", file_ptr);
exit(0);
}
void Fopen(const char * restrict filePath, const char * restrict mode, FILE * restrict filePtr)
{
if ( (filePtr = fopen(filePath, mode)) != NULL)
printf("file pointer is %p\n", filePtr);
}
On Command Line:
[jim@cola c++]$ ./readFile
file pointer is 0x740010
File pointer is (nil)
The only explanation is that a copy of FILE * is being passed to Fopen. How can i pass pointer by ref?
Your
Fopenfunction changes the value of its localfilePtrand then throws that value away. Nothing in your code can change the value offile_ptrin the caller. You just pass a NULL to the function.You want this: