'Hexadecimal value not being written correctly to a char using scanf

I am programming in C and using scanf to write two values to two different variables and then output that using printf. However, when I type the first of the two values, it just comes back as ($00). The second value seems to work fine however, and will report back what I typed. I'm assuming this is just a scanf problem. Here is a part of the code where the problem takes place. Why could this be?

intA = strcmp(command, "write");
if(intA != 0) intA = strcmp(command, "w");
if(intA == 0){
    printf("location to write to, value> ");
    scanf(" %x %x", &charA, &charB);
    ram[charA] = charB;
    printf("($%.2x): $%.2x\n\n", charA, ram[charA]);
}


Solution 1:[1]

You are using %x, which is for reading an unsigned int. Apparently you are trying to read values of type unsigned char. So you need a length modifier. Try this:

scanf("%hhx%hhx", &charA, &charB);

Without the hh modifier, scanf will write an int's worth of bytes (probably 2 or 4) on top of charA and charB, thus clobbering some nearby memory.

Specifically: you said "when I type the first of the two values, it just comes back as 00. The second value seems to work fine however". So if you type, say, 12 for your location and 34 for your value, scanf is trying to write either 0034 or 00000034 into charB, and the extra 00's are spilling over on top of charA. (That's after scanf tried to write either 0012 or 00000012 into charA, which similarly spilled over and overwrote something else.)

Alternatively, you could declare your charA and charB variables as being of type unsigned int, instead. There's not much to be gained in making them characters. (And, as we've seen, there's something to be lost!)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1