Alexander Bollbach
Alexander Bollbach

Reputation: 659

Simple way to print pointers in decimal

I find myself wanting to print out the pointer to a memory address at each given iteration of a function call. I wish to see if the location in memory is advanced linearly at each iteration (because I suspect this may be the case based on the nature of the API). Viewing the resultant hexadecimal logs in the console doesn't conveniently help me and so I'd prefer the decimal value. What is the simplest way of print out these address' decimal value?

Upvotes: 1

Views: 6110

Answers (3)

Ryan
Ryan

Reputation: 14649

You should cast the pointer to an integer type. A safe way to do it would be to first check the byte sizes of the data types:

if(sizeof(unsigned long) == sizeof(void *)) {
    unsigned long base_10_address = (unsigned long)pointer;
    printf("%lu\n", base_10_address); 
}

Upvotes: 1

To do this portably (in a way that will work even if pointers and ints are different sizes, you can use:

#include <inttypes.h>

printf("%" PRIuPTR, (uintptr_t)some_pointer);

Upvotes: 6

John3136
John3136

Reputation: 29266

For most purposes printf("ptr=%d\n", p); will do it. Sure there may be academic cases where it doesn't work, but 99% of the time it'll be ok.

Edit: ok, so printf("ptr=%lu\n", (unsigned long)p); is safer, or even %llu.

Upvotes: 4

Related Questions