Camil Staps Camil Staps - 1 year ago 135
C Question

Printf pointer in decimal notation

How can I print a pointer in decimal notation?

None of the below produce the desired result when compiling with

. I understand the errors, and do want to compile with
. But then how can I print a pointer in decimal notation?

#include <stdio.h>
#include <stdlib.h>

int main() {
int* ptr = malloc(sizeof(int));
printf("%p\n", ptr); // Hexadecimal notation
printf("%u\n", ptr); // -Wformat: %u expects unsigned int, has int *
printf("%u\n", (unsigned int) ptr); // -Wpointer-to-int-cast

(This is needed because I'm using the pointers as node identifiers in a dot graph, and
is not a valid identifier.)

Answer Source

C has a datatype named uintptr_t, which is large enough to hold a pointer. One solution is to convert (cast) your pointer to (uintptr_t) and print it like shown below:

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

int main(void) 
    int* ptr = malloc(sizeof *ptr);
    printf("%p\n", (void *)ptr);                 // Hexadecimal notation
    printf("%" PRIuPTR "\n", (uintptr_t)ptr);
    return EXIT_SUCCESS;

Note that %p expects a void* pointer, gcc will warn if you compile your code with -pedantic.

string format for intptr_t and uintptr_t seems to be relevant too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download