You need to have a main()
function. C doesn't execute random code that's not inside a function. Try rewriting it to look like this:
void getname(char *fname)
{
fname = (char *)malloc(30);
gets(fname);
}
int main(void){
char* fname;
getname(fname);
puts(fname);
}
Ok, now we can analyze it.
What happens is that when you pass a pointer (or any variable) to a function, the pointer gets copied. When you do fname = malloc(30);
, the fname
in the function gets set to the pointer from malloc
, but the original fname
in main remains the same. So when getname
returns to main
, fname
still is uninitialized.
What you want to do is either allocate fname
in main, or return a pointer from getname
. So something like this would work:
void getname(char *fname)
{
gets(fname);
}
int main(void){
char* fname = malloc(30); // OR
char fname2[30];
getname(fname);
puts(fname);
}
And so would this:
char* getname(void)
{
fname = (char *)malloc(30);
gets(fname);
return fname;
}
int main(void){
char* fname = getname();
puts(fname);
}