I have this working code that assigns fixed values to some unsigned char variables:

#include <stdio.h>
#include <stdlib.h>


int main2() 

{   
 unsigned char a,b;
    a=1,b=2;
    a=(a+b)/2;
    printf("\nAverage: %d\n%18d",a,sizeof(a));  

return 0;
}

But when I try reading in the values instead, like so:

#include <stdio.h>
#include <stdlib.h>


int main() 

{   
 unsigned char a,b;
    scanf(" %d", &a);   scanf(" %d", &b);
    a=a,
    b=b,
    a=(a+b)/2;
    printf("\nAverage: %d\n%18d",a,sizeof(a));  

return 0;
}

it doesn't work. Why not? It seems that scanf takes only the last value when I print the sum.

This is my best attempt to fix the code:

#include <stdio.h>
#include <stdlib.h>


int main()
{
unsigned char b;
unsigned short int a;
    scanf(" %u", &a);
    scanf(" %u", &b);
    b=b;{

    b=(a+b);
unsigned short int a;
    scanf(" %u", &a);{  
    
    
    b=(a+b)/3;
    printf("\nAverage: %u",b);  
    printf("\n   sizeof: %d",sizeof(b));
    
    
    }
            
}
return 0;   
}
2

There are 2 best solutions below

1
Evert_B On

General advice: take warnings to heart when compiling. Copying and pasting your code gave me the following:

main.c:8:14: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘unsigned char *’ [-Wformat=] 8 | scanf(" %d", &a);

So taking all warning into account, I can re-order your first program to this (which works!):

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a, b;
    scanf(" %d", &a);
    scanf(" %d", &b);
    // a = a, --> has no effect
    // b = b, --> has no effect
    a = (a + b) / 2;
    printf("\nAverage: %d\n%18d", a, sizeof(a));
    return 0;
}

If you really do want to use unsigned chars, go with %hhu:

unsigned char a, b;
scanf(" %hhu", &a);
scanf(" %hhu", &b);
0
Vlad from Moscow On

From the C Standard (7.21.6.2 The fscanf function)

13 If a conversion specification is invalid, the behavior is undefined.

And you are using invalid conversion specifiers with declared objects as for example:

unsigned char a,b;
scanf(" %d", &a);   scanf(" %d", &b);

The conversion specifier d is designed to deal with objects of the type int not with objects of the type unsigned char.

Instead you need to write:

unsigned char a,b;
scanf(" %hhu", &a);   scanf(" %hhu", &b);

or instead of:

unsigned short int a;
scanf(" %u", &a);{  

you need to write:

unsigned short int a;
scanf(" %hu", &a);{  

Also the sizeof operator returns values of the type size_t. So to output such values you need to use the conversion specifier zu instead of d:

printf("\nAverage: %d\n%18zu\n",a,sizeof(a)); 

or for example:

printf("\n   sizeof: %zu\n",sizeof(b));