Navigation

Sunday 28 October 2018

Why does C scanf only accept char a[n]?

#include <stdio.h>
int main(void)
{
    char *name;
    scanf("%s", name);
    printf("You've entered %s\n", name);

    return 0;
}
Look at the above code.
The book says it may or may not be compiled.
It can be compiled on my Linux. But it runs and I type hello, it is not right.
hello
You've entered (null)
I know name is an uninitialized pointer why may point to anything.
So the proper way to correct this is char name[81];
Now I made some change.
I initialize name at the very beginning, like this:
#include <stdio.h>
int main(void)
{
    char *name = "aaa";
    scanf("%s", name);
    printf("You've entered %s\n", name);

    return 0;
}
It can also be compiled. But when I type hello, I get this:
[Tom@localhost ~]$ ./a.out 
hello 
Segmentation fault (core dumped)
Now that name has been initialized which in my understanding should be given an specific address.
Why it still fails to work ?


Here

No comments:

Post a Comment