scanf can't scan into uint8_t

c

Solution

The `%d` is wrong, because it means you are passing `int *` but you actually want to pass `uint8_t *`. You will need to use the appropriate macro:

#include <inttypes.h>
...
sscanf(foo, "%2" SCNu8 " %2" SCNu8, &d1, &d2);

Most compilers should be giving you warnings about your version of the code. Here is Clang's output:

test2.c:8:24: warning: format specifies type 'int *' but the argument has type
      'uint8_t *' (aka 'unsigned char *') [-Wformat]
sscanf(foo, "%2d %2d", &d1, &d2);
             ~~~       ^~~
             %2s
test2.c:8:29: warning: format specifies type 'int *' but the argument has type
      'uint8_t *' (aka 'unsigned char *') [-Wformat]
sscanf(foo, "%2d %2d", &d1, &d2);
                 ~~~        ^~~
                 %2s
2 warnings generated.

For `uint8_t`, this does not apply to `printf()`, since the `uint8_t` will always be promoted to `int` before it is passed to `printf()`.

Problem

When I try to use `scanf` with `uint8_t`, I get crazy results. Using `int`, I get the expected output "08 - 15". Using `uint8_t`, I get "00 - 15". ``` const char *foo = "0815"; uint8_t d1, d2; // output: 00 - 15 (!!!) // int d1, d2; // output: 08 - 15 sscanf(foo, "%2d %2d", &d1, &d2); printf("%02d - %02d\n", d1, d2); ``` I'm using GCC.

Original source