3

I tried to print an unsigned int* in C. I used %X but the compiler said:

" format %x expects argument of type unsigned int, but argument 3 has type unsigned int* ".

I also used "%u" but I got the same error again.

Can anybody help me?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Mahan
  • 99
  • 1
  • 8
  • Compiler is telling 100% correct. Use `%p` format specifier to print the pointer type variable. For e.g `unsigned int *ptr = &someAddr; printf("Address %p\n", (void*)ptr);` – Achal Feb 24 '20 at 07:15

2 Answers2

4

If you want to print a pointer, you need to use %p format specifier and cast the argument to void *. Something like

 printf ("%p", (void *)x);

where x is of type unsigned int*.

However, if you want to print the value stored at x, you need to dereference that, like

printf ("%u", *x);
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

If you want to print the pointer itself you should use the format %p:

// Create a pointer and make it point somewhere
unsigned int *pointer = malloc(sizeof *pointer);

// Print the pointer (note the cast)
printf("pointer is %p\n", (void *) pointer);

Or if you want to print the value that the pointer is pointing to, then you need to dereference the pointer:

// Create a pointer and make it point somewhere
unsigned int *pointer = malloc(sizeof *pointer);

// Set the value
*pointer = 0x12345678;

// And print the value
printf("value at pointer is %08X\n", *pointer);

While the %p format specifier is uncommon, most decent books, classes and tutorials should have information about dereferencing pointers to get the value.

I also recommend e.g. this printf (and family) reference which lists all standard format specifiers and possible modifiers.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621