I have the following code:
#include <stdio.h>
char * lookLine (FILE *fichero)
{
char p[25];
fgets (p, sizeof (p), fichero);
return p;
}
int main (void) {
printf ("%s\n", lookLine (fopen ("suma.c", "r")));
return 0;
}
And I get the following output:
#��x�
Not nice. My intention is to print out the first line of the file whose name "suma.c". It should print out the following:
#include <stdio.h>
Nevertheless, if I print out the content of p
string into the same lookFile
function, it does it fine:
#include <stdio.h>
void lookLine (FILE * fichero)
{
char p[25];
fgets (p, sizeof (p), fichero);
printf ("%s\n", p);
}
int main (void) {
lookLine (fopen ("suma.c", "r"));
return 0;
}
And the output I get now is the correct one:
#include <stdio.h>
My reasoning is this: by using fgets
I save the string of the first line of "name.c" in the p
array and I return its address, which is taken by the second argument of printf
function in main
.
But I have found out that this only works when I use the printf
function directly into the same lookLine
function...
Please, could someone tell me what's really going on here?
It's because you are returning a pointer to a local array from the read
function.
Remember that local variables are stored on the stack, and that includes arrays. And when the function returns that stack space is reclaimed by the compiler to be used by other function calls. So you have a pointer pointing to another function's memory.