How to take character input in an array in C?

25,595

Solution 1

For the %c specifier, scanf needs the address of the location into which the character is to be stored, but printf needs the value of the character, not its address. In C, an array decays into a pointer to the first element of the array when referenced. So, the scanf is being passed the address of the first element of the name array, which is where the character will be stored; however, the printf is also being passed the address, which is wrong. The printf should be like this:

printf("%c", name[0]);

Note that the scanf argument is technically ok, it is a little weird to be passing an array, when a pointer to a single character would suffice. It would be better to declare a single character and pass its address explicitly:

char c;
scanf("%c", &c);
printf("%c", c);

On the other hand, if you were trying to read a string instead of a single character, then you should be using %s instead of %c.

Solution 2

Either Read a single char

char name[2];
scanf("%c",name);
printf("%c",name[0]);

Or read a string

char name[2];
scanf("%1s",name);
printf("%s",name);
Share:
25,595
Allen He
Author by

Allen He

Updated on December 10, 2020

Comments

  • Allen He
    Allen He over 3 years
    char name[2];
    scanf("%c",name);
    printf("%c",name);
    

    I am just starting to learn C. I'm curious about the above code, what I got from the printf output, is not the same with the character I typed in. Rather the output was some funny looking symbol. Can someone explain this to me?