Search code examples
arrayscstringscanfformat-specifiers

Using Scanf() for taking input for both string and integer


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


Solution

  • Your char c[2]; variable is not a large enough array to hold a 2-character string plus the required nul-terminator. If you know that the input will be no more than 2 characters, changing to char c[3]; should be sufficient; however, for added safety, you can include a limit on how many characters will be read by the scanf call, using a format specifier like %2s (or, more generally, for an array such as char buff[n]; use a value of n - 1 in that format specifier).

    As it stands, you have undefined behaviour – and this may include overwriting the value given for b (with the zero that should be the nul-terminator).