Navigation

Showing posts with label scanf. Show all posts
Showing posts with label scanf. Show all posts

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

Sunday, 21 October 2018

Is a the same as &a in scanf in C language ?

#include <stdio.h>
int main(void)
{
    float rootbeer[10];

    scanf("%f", rootbeer);

    printf("%f\n", *rootbeer);

    return 0;
}
Look at the above code.
It works well.
In my understanding, rootbeer is the same as rootbeer + 0, which is pointer to a floating number.
Now I change rootbeer in scanf to &rootbeer.
#include <stdio.h>
int main(void)
{
    float rootbeer[10];

    scanf("%f", &rootbeer);

    printf("%f\n", *rootbeer);

    return 0;
}
I anticipated an error message because I think &rootbeer is pointer to array of 10 of float.
However, the changed code can also be compiled and works perfectly.
I wonder why.
Is a the same as &a in scanf in C language ?

Here

gcc -std=c11 -Wall -Werror ***.c   should be able to show all errors, including those undefined behaviour that still can be compiled.