The first row which should only store one character of its own stores all the characters of different rows. Why? can anyone explain to me this?
scanf("%s", chr[i]);
%s
reads a whole string until it encounters a white space character, such as newline \n
, and writes it (excluding the white space character) into the first dimension; not only one character.
You also forgot that since you are trying to read a string a \0
is automatically appended to each string, but since the declaration of chr
there is just place for one character in a dimension, not two.
A multi-dimensional array is allocated continously in memory, which provides the effect that the \0
character for the string in the previous dimension is stored at the first and only character of the next dimension; in the next iteration scanf
overwrites then this \0
character to store the second character but again writes the \0
of this string into the first an only object of the following dimension and goes so on and on for each iteration, which ends up in a complete mess of Undefined Behavior, plus the \0
of the last string is written beyond the bounds of the complete multi-dimensional array.
So you can´t even say that they were stored in just one dimension, which isn´t the case, even if it seems like it would.
For more information about Undefined Behavior look at this question:
Undefined, unspecified and implementation-defined behavior
Rather use
scanf(" %c", &chr[i][0]);
with the %c
format specifier to read only one character per iteration and implement a white space character before the %c
format specifier to catch the newline \n
left in stdin
by the scanf
consumption of the previous loop walkthrough or any leading white space.
Also, change:
for(int i = 0; i<n; i++) {
printf("\n%s\n", chr[i]);
to
for(int i = 0; i<n; i++) {
printf("\n %c \n", chr[i][0]);
The whole code shall then be:
#include <stdio.h>
int main(void) {
int n;
scanf("%d", &n);
char chr[n][1];
for(int i = 0; i<n; i++) {
printf("Enter the %d character?\n", i);
scanf(" %c", &chr[i][0]);
}
// printing
for(int i = 0; i<n; i++) {
printf("\n %c \n", chr[i][0]);
}
return 0;
}