I was writing a simple C program to take inputs from user for different variables using scanf()
as follows:
#include <stdio.h>
int main(){
int a, b;
scanf("%d %d", &a, &b);
printf("%d\n",a);
printf("%d\n",b);
return 0;
}
The output for this is coming completely fine, as expected:
input: 10 23
output: 10
23
But then I also tried to take input for a string array, as follows(here char c[2]
is a string array):
#include <stdio.h>
int main(){
int a, b;
char c[2];
scanf("%d %d %s", &a, &b, c);
printf("%d\n",a);
printf("%d\n",b);
printf("%s\n",c);
return 0;
}
And now the output was something unexpected:
input: 10 23 AM
output: 10
0
AM
Here, as it can be seen that the value being printed for variable b
is coming to be 0
, instead of the expected 23
. How did taking input for a string array change the value of variable b
?
Can someone help figure out, what wrong(of course silly mistake) have I done?emphasized text