开发者

warning of printf format not suitable for a variable of type uint32_t

开发者 https://www.devze.com 2023-03-14 18:36 出处:网络
I just learned about C, and I know this is a basic question, but I just can not figure out how I can solve this. For instance, I have a line of

I just learned about C, and I know this is a basic question, but I just can not figure out how I can solve this. For instance, I have a line of

printf("value :%d\n",var.value);

the format does not suit, as it shows error below

*format ‘%d’ expects开发者_运维技巧 type ‘int’, but argument 3 has type ‘uint32_t *'

I have already checked at this reference of cplusplus : cplusplus print ref

but it does not explicitly state how to print the value with the type is uint32_t * (likewise uint16_t).

Any explanation will very appreciated.


You were trying to print a pointer to an uint32_t as an int. You have to do two things:

  1. dereference the pointer so you can print the uint32_t and not the pointer.
  2. use the correct printtf format specifier

The correct way to format an uint32_t is to use the macro PRIu32 , which expands to the format character as a string.

That is, you do

printf("%"PRIu32"\n", *var.value);

You're probably on a common platform where an unsigned int is the same as uint32_t, in which case you could just do:

printf("%u\n", *var.value);

(note, %u instead of your code that used %d , %u is for an unsigned int, while %d is for a signed int)


If you want the pointer use %p,

printf("value :%p\n",var.value); 

If you want the dereferenced unsigned int value use

printf("value :%u\n",*(var.value)); 

This assumes that the value field in var is actually a pointer to uint32_t - that's what your warning text implies.

It's nice that you get a warning here - printf is not type-safe, so frequently misuse of the API just results in a sudden runtime malfunction (eg. crash or worse, undetected memory corruption).

0

精彩评论

暂无评论...
验证码 换一张
取 消