2

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
markoj
  • 150
  • 10

2 Answers2

3

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Just as an addition, in case of the %hhu conversion specifier being unavailable, you can do:

#include<stdio.h>
unsigned char inp_u8(void){
    unsigned int x;
    scanf("%u",&x);
    return x&0xFF;
}
markoj
  • 150
  • 10