Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best portable way to represent pointer as string in C++?

Tags:

c++

pointers

I need to represent pointers as strings to the user. Sometimes the values might be saved to a file and transferred to a computer with different architecture (32 vs 64 bit is the main issue currently) and loaded from text file to be compared - I'm only going to compare loaded values with each other, but I'd still prefer to compare numbers than strings.

I'm currently using:

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

but I wonder if this is portable (Windows and Linux are only important at this stage though), and whether this would break once 128-bit systems show up?

Edit: unless I decide to use uint64_t, and decide that 64bit is the rooftop, this cannot be done because some 64bit pointer might be outside 32bit integer range. So, I decided that it would be safer to compare strings even if it's slower.

like image 300
Milan Babuškov Avatar asked Jun 03 '09 20:06

Milan Babuškov


People also ask

Can a pointer store a string?

More correctly, a pointer cannot store a string as well as anything, a pointer can point to an address containing data of the pointer's type. Since char* is a pointer to char , it points exactly to a char .

Is a CString a pointer?

a CString will be an array of char and a char* will be a pointer into the array of char with which you can iterate the characters of the string. Actually from MSDN: CString is based on the TCHAR data type.

Can I assign string to pointer?

Creating a pointer for the string The variable name of the string str holds the address of the first element of the array i.e., it points at the starting memory address. So, we can create a character pointer ptr and store the address of the string str variable in it. This way, ptr will point at the string str.

How do you define CString?

A "C string" is an array of characters that ends with a 0 (null character) byte. The array, not any pointer, is the string. Thus, any terminal subarray of a C string is also a C string.


2 Answers

For pointers, always use %p---it's a format specifier specially designed for printing pointers in the right format. :-)

like image 97
Chris Jester-Young Avatar answered Nov 03 '22 00:11

Chris Jester-Young


I'd do this:

std::cout << p;

If you have your heart set on cstdio:

printf("%p", p);
like image 43
Fred Larson Avatar answered Nov 03 '22 02:11

Fred Larson