What is the best portable way to represent a pointer as a string in C ++?

I need to represent pointers as strings for the user. Sometimes the values ​​can be saved to a file and transferred to a computer with a different architecture (32 vs 64 bit - the main problem at present) and loaded from a text file for comparison - I'm going to compare only the downloaded values ​​with each other, but I still prefer compare numbers than strings.

I am currently using:

SomeClass* p;
...
printf("%ld", (uintptr_t)p);

but I wonder if it is portable (only Windows and Linux are important at this stage), and will it be interrupted after the advent of 128-bit systems?

Edit : if I didn’t decide to use uint64_t and decided that it was a 64-bit roof, this cannot be done because some kind of 64-bit pointer might be outside the 32-bit integer range. So, I decided that it would be safer to compare strings, even if they are slower.

+5
source share
6 answers

For pointers, always use %p--- this is a format specifier specifically designed to print pointers in the correct format. :-)

+20
source

I would do this:

std::cout << p;

If you have your heart set on cstdio:

printf("%p", p);
+9
source

printf % p, , , :

printf( "%p", p );

++, ostreams :

#include <iostream>
using namespace std;;

class A {};

int main() {
    A a;
    cout << &a << endl;
}

:

0x22ff6f
+7

%p?

printf("%p", p);

, (, , NULL ).

+3

:

cout << p << endl;

( ) . , unsigned long.

128- , . 64- 16,8 .

0

printf ( "% # x", p);

(0x...) .

0

All Articles