ccharscanfconversion-specifier

Why does scanf set the first value to 0?


I am using scanf to get an input. But when I run this code:

#include<stdio.h>

int main(){
  unsigned char in,b;
  scanf("%u %u",&in,&b);
  printf("%u %u\n",in,b);
  return 0;
}

when I input, for example, 12 3 , the output is 0 3.

This also happends when I instead of scanf("%u %u",&in,&b); write scanf("%u",&in);scanf("%u",&b);.

Thanks for reaching out.


Solution

  • This call of scanf

    unsigned char in,b;
    scanf("%u %u",&in,&b);
    

    invokes undefined behavior because the function expects that its second and third arguments are pointers to objects of the type unsigned int while actually they are pointers to objects of the type unsigned char.

    Instead you have to use the length modifier hh with the conversion specifier u

    scanf("%hhu %hhu",&in,&b);
    

    From the C Standard (7.21.6.2 The fscanf function)

    11 The length modifiers and their meanings are:

    hh Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to signed char or unsigned char.