I wrote the following:
#include <stdio.h>
#include <string.h>
char* getString();
char* getString(){
char str[10];
gets(str);
return str;
}
int main() {
char* s;
s=getString();
strcpy(s,"Hi");
puts(s);
return 0;
}
I know that the length of str must be less than 10, but even when I wrote just “Hi”, nothing was being printed. as far as I see it, it should be Ok. the compiler says that fgets is dangerous and should not be used.
What is the reason that nothing being printed on the screen?
This is wrong!!! Local variables are invalidated when their scope exits; thus using returned array is undefined behavior. You have to malloc a string and return it: