Scanf char on array in c
char name[2];
scanf("%c",name);
printf("%c",name);
Hey guys, I'm just starting to learn C. I'm wondering how the above code that I got from the printf output is not the same with the character I entered. Rather, the result was some kind of funny symbol, can someone explain this to me? Thank.
source to share
The specifier %c
scanf
needs the address of the location where the character is to be stored, but printf
it needs the character's value, not its address. In C, an array is split into a pointer to the first element of the array when referenced. Thus, scanf
the address of the first element of the array is passed name
in which the character is stored; however, the printf
address is also transmitted, which is incorrect. printf
should look like this:
printf("%c", name[0]);
Note that the argument is scanf
technically okay, it's a little weird to pass an array when a pointer to one character would suffice. It would be better to declare one character and explicitly pass its address:
char c;
scanf("%c", &c);
printf("%c", c);
On the other hand, if you tried to read a string instead of a single character, you should use %s
instead %c
.
source to share