c - Trying to return char array via pointer and it's giving incorrect results -
my code is:
#include <stdio.h> #include <string.h> char *getuserinput() { char command[65]; //ask user valid input printf("please enter command:\n"); fgets(command, 65, stdin); //remove newline command[strcspn(command, "\n")] = 0; return command; } int main() { char *reccommand = getuserinput(); printf("%s", reccommand); return 0; }
when code executed, console:
please enter command: test <-- command entered *weird unknown characters returned console*
why there weird unknown characters being returned console instead of "test"?
it because returning value of local variable. try putting this:
char *getuserinput() { static char command[65]; //ask user valid input printf("please enter command:\n"); fgets(command, 65, stdin); //remove newline command[strcspn(command, "\n")] = 0; return command; }