I am having an issue understanding why the %x is not working in this code. Since int_ptr is a pointer it has a hex address in the memory so writing %x should work. Could anyone please help.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <stdio.h>
int main() {
int int_var = 5;
int *int_ptr;
int_ptr = &int_var; // put the address of int_var into int_ptr
printf("int_ptr = 0x%08x\n", int_ptr);
printf("&int_ptr = 0x%08x\n", &int_ptr);
printf("*int_ptr = 0x%08x\n\n", *int_ptr);
printf("int_var is located at 0x%08x and contains %d\n", &int_var, int_var);
printf("int_ptr is located at 0x%08x, contains 0x%08x, and points to %d\n\n",
&int_ptr, int_ptr, *int_ptr);
}
I am compiling it from the command line and this is what I am getting:
addressof2.c: In function ‘main’:
addressof2.c:9:4: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("int_ptr = 0x%08x\n", int_ptr);
^
addressof2.c:10:4: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int **’ [-Wformat=]
printf("&int_ptr = 0x%08x\n", &int_ptr);
^
addressof2.c:13:4: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("int_var is located at 0x%08x and contains %d\n", &int_var, int_var);
^
addressof2.c:15:7: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int **’ [-Wformat=]
&int_ptr, int_ptr, *int_ptr);
^
addressof2.c:15:7: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘int *’ [-Wformat=]
First of all %x writes unsigned int. There is no guarantee that pointer size = unsigne int size.
As there is no format specifier which takes uintptr_t, you need to manualy check your pointer size in program and then select correct format specifier.