Is this wrong?Code:char *fun (void) { char str [30]; fgets (str, 30, stdin); return str; }
Isn't it possible to return a pointer to a local variable?
I get a warning when compiling.
This is a discussion on char *fun () within the C Programming forums, part of the General Programming Boards category; Code: char *fun (void) { char str [30]; fgets (str, 30, stdin); return str; } Is this wrong? Isn't it ...
Is this wrong?Code:char *fun (void) { char str [30]; fgets (str, 30, stdin); return str; }
Isn't it possible to return a pointer to a local variable?
I get a warning when compiling.
It is better to do:
saves memory, use it like this:Code:int fun(char *str) { fgets(str,30,stdin); return 0; }
once that command is done, string will be set to whatever was input.Code:fun(string);
local variables only exist in the function they are declared in, so str will cease to exist when your function exits. Therefore you are returning a pointer to nothing.char str [30];
What you need to do is declare str as static, this means it will remain in memory.
Or do as Brian said.Code:char *fun (void) { static char str [30]; fgets (str, 30, stdin); return str; }
![]()
All spelling mistakes, syntatical errors and stupid comments are intentional.