Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take character input in an array in C?

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?

like image 805
Allen He Avatar asked Aug 06 '17 17:08

Allen He


People also ask

Can we store character in array in C?

This article will help you understand how to store words in an array in C. To store the words, a 2-D char array is required. In this 2-D array, each row will contain a word each. Hence the rows will denote the index number of the words and the column number will denote the particular character in that word.

How will you accept the name of user in a character array?

Just use 'name' itself.

How do you declare a character array in C?

char arr[] = {'c','o','d','e','\0'}; In the above declaration/initialization, we have initialized array with a series of character followed by a '\0' (null) byte. The null byte is required as a terminating byte when string is read as a whole.

Can we use character in array?

The characters in a Character Array can be accessed normally like in any other language by using []. Strings can be stored in any manner in the memory. Elements in Character Array are stored contiguously in increasing memory locations. All Strings are stored in the String Constant Pool.


2 Answers

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.

like image 130
pat Avatar answered Sep 21 '22 03:09

pat


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);
like image 29
Uri Goren Avatar answered Sep 18 '22 03:09

Uri Goren