Thorvason Thorvason - 2 months ago 6x
C++ Question

How to change the cout format for pointers

I have to write a C++ program on in VS which does the same as a previously written programm for Solaris which is compiled with gcc.

The following "problem" occured:

int var1 = 42;
int* var1Ptr = &var1;
cout << "Address of pointer " << var1Ptr << endl;

This code returns in the solaris program a 0x indexed address (0x08FFAFC).

In my VS code it returns as 008FFAFC.

Since we only do comparison within the code it would be fine, but the supportteam have their own tools which extract data from the logs which is looking for those 0x indexed values. Is there a way to format it like this without adding the 0x prefix everytime we write into the logs?

cout << "Maybe this way: " << hex << int(&var1Ptr) << endl;

doesn't have the effect I wanted.


A little helper class:

namespace detail {

    template<class T>
    struct debug_pointer
        constexpr static std::size_t pointer_digits()
            return sizeof(void*) * 2;
        static constexpr std::size_t width = pointer_digits();

        std::ostream& operator()(std::ostream& os) const
            std::uintptr_t i = reinterpret_cast<std::uintptr_t>(p);
            return os << "0x" << std::hex << std::setw(width) << std::setfill('0') << i;
        T* p;

        std::ostream& operator<<(std::ostream& os, debug_pointer const& dp) {
            return dp(os);


offered via a custom manipulator...

template<class T>
auto debug_pointer(T* p)
    return detail::debug_pointer<T>{ p };

allows us this expression:

int i;
std::cout << debug_pointer(&i) << std::endl;

Which will yield either an 8-digit or 16-digit hex pointer value, depending on your architecture (mine is 64-bit):