Reputation: 564
Is it possible to change the value being pointed to by a FILE pointer inside a function in C by passing by reference?
Here is an example to try and illustrate what I'm trying to do, I can modify the integer but not the file pointer, any ideas?
int main (void)
{
FILE* stream;
int a = 1;
configure_stream(rand() % 100, &a, &stream);
return 0;
}
void configure_stream(int value, int* modifyMe, FILE* stream)
{
*modifyMe = rand() % 100;
if (value > 50)
{
*stream = stderr;
}
else
{
*stream = stdout;
}
}
Upvotes: 0
Views: 1704
Reputation: 182764
Try
void configure_stream(int value, int* modifyMe, FILE **stream)
^
*stream = stderr;
What you were trying wasn't correct:
void configure_stream(int value, int* modifyMe, FILE* stream)
*stream = stderr; /* Assign FILE * to FILE. */
You should call it: configure_stream(..., &stream);
Upvotes: 2
Reputation: 1267
I think you want to declare your configure_stream as follows
void configure_stream(int value, int* modifyMe, FILE** stream)
{
*modifyMe = rand() % 100;
if (value > 50)
{
*stream = stderr;
}
else
{
*stream = stdout;
}
}
and use it with
configure_stream(rand() % 100, &a, &stream)
This gets a pointer pointing to a FILE pointer. With the pointer to the pointer you can modify the FILE pointer and without loosing it in the big jungle of memory
Upvotes: 2
Reputation: 2951
You are passing configure_stream a pointer to a FILE pointer. So the parameter should be declared as FILE **
Upvotes: 1