Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading