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.

+3


source to share


4 answers


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

.

+4


source


Read one char

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

      



Or read the line

char name[2];
scanf("%1s",name);
printf("%s",name);

      

+3


source


You need% s as the name contains 2 elements. % c is used for a single character, so if you want the user to enter something eg. "as" (without ""), and you need% s to print the program.

char name[2];

scanf(" %s", name);
printf("%s",name);

      

0


source


if you give your input which contains characters less than or equal to two, you will get correct output just like your input, if your input contains characters greater than 3 then it doesn't work.

-2


source







All Articles