Reputation: 367
I have a dummy function char * getFileName() that just returns a pointer to an array of chars:
char * getFileName () {
char buff[11] = "index.html";
char *p;
p = buff;
printf ("name of the file: %s\n", p);
return p;
}
In my case this pointer is the name is the name of a file I want to open and read from main:
int main() {
char *fp;
FILE *file;
fp = getFileName();
int c;
file = fopen(fp, "r");
if (file) {
while ((c = getc(file)) != EOF) {
putchar(c);
}
fclose(file);
}
return (0);
}
However, I can't open that file using the pointer value as a name, although when I print fp, I get the correct name if the file: index.html. Any suggestions what I could be missing? Thank you :)
Upvotes: 0
Views: 1662
Reputation: 21213
You are returning a pointer to a local variable - by the time getFileName()
returns, buff
is destroyed and the value of p
points to memory that is no longer usable.
If you really want to do this, you must make buff
a static
variable:
char *getFileName(void) {
static char buff[] = "index.html";
char *p;
p = buff;
printf ("name of the file: %s\n", p);
return p;
}
static
variables are not stack-allocated; they are.. well.. statically allocated.
A couple of other important details:
f
that doesn't receive any arguments should be declared as f(void)
.buff
, because you initialized it with "index.html"
.Upvotes: 1