I'm trying to print the address(reference) of a variable in hex and that too in upper case. But I see that I'm able to print the hex equivalent of 77 in upper case, but not the address(reference) of a variable. Can somebody help me please?
The following is the program I have the difficulty with.
#include <iostream>
#include <string>
using namespace std;
void print_nb_of_items(const int nb_of_apple, const int& nb_of_pens)
{
cout << "Number of apples = " << nb_of_apple << endl;
cout << "Number of pens = " << nb_of_pens << " Address = " << uppercase << hex << &nb_of_pens << endl;
cout << "Hex output in uppercase = " << uppercase << hex << 77 << endl;
}
/* The main function */
int main(int argc, char * argv[])
{
int nb_apple = 24;
int nb_pens = 65;
print_nb_of_items(nb_apple, nb_pens);
return 0;
}
The output for the program I got is:
Number of apples = 24
Number of pens = 65 Address = 0xbffbd438
Hex output in uppercase = 4D
I want the address to be printed as: 0xBFFBD438. How do I do that?
"I want the address to be printed as: 0xBFFBD438. How do I do that?"
Well, @MatsPetterson hit the nail on the head in his comment, casting the address value to a uintptr_t
cout << "Number of pens = " << nb_of_pens
<< " Address = 0x" << uppercase << hex
<< uintptr_t(&nb_of_pens) << endl;
// ^^^^^^^^^^ ^
just makes it work fine (see fully working sample here please).
To explain in more depth:
The implementation of
std::ostream operator<<(ostream& os, void* ptr);
isn't further specified by the standard, and may simply not be affected by/considering the std::uppercase
I/O manipulator. Conversion of the pointer value to a plain number, will take the std::uppercase
and std::hex
I/O manipulators into effect.
Like printf("%p", &obj)
, the stream output format of a pointer is entirely unspecified. By convention we get a hexadecimal value and, on some systems, that abides by std::uppercase
(and friends). But you cannot rely on that. Those I/O manipulators are there for numbers, not pointers.
You can actually transform your pointer into a number to guarantee the behaviour you want:
cout << "Number of pens = " << nb_of_pens
<< " Address = " << uppercase << hex << uintptr_t(&nb_of_pens)
<< endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With