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?
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.
Just use 'name' itself.
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.
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.
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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With