How to simulate printf's %p format when using std::cout?
Depending on wheter or not you want to use more formatting options printf gives, you could consider using sprintf
By it, you could format a string just like you'd do with printf, and afterwards print it out with
However, this would involve using a temporary char array so the choice depends.
unsigned char *teta = ....; ... char formatted[ 256 ]; //Caution with the length, there is risk of a buffer overflow sprintf( formatted, "data at %p\n", teta ); std::cout << formatted;
unsigned char *teta = ....; ... printf("data at %p\n", teta); // prints 0xXXXXXXXX
How can I print variable address using
iostreams? Is there a
std::??? feature like
std::hex to do this kind of conversion (address -> string), so
std::cout << std::??? << teta << std::endl will print that address?
(no sprintf's, please ;))
Point p2 = p1;
you simply copy the values of p2 onto p1 (most likely). The memory is independent. If you did instead:
Point* p2 = &p1;
then p2 will be a pointer onto p1 (printing its value will give you the begining of the memory block, you could then try the sizeof to get the size of the block).
You cannot depend on
%p displaying a
0x prefix. On Visual C++, it does not. Use
%#p to be portable.
Where is `%p` useful with printf?
They do not do the same thing. The latter
printf statement interprets
b as an
unsigned int, which is wrong, as
b is a pointer.
unsigned ints are not always the same size, so these are not interchangeable. When they aren't the same size (an increasingly common case, as 64-bit CPUs and operating systems become more common),
%x will only print half of the address. On a Mac (and probably some other systems), that will ruin the address; the output will be wrong.
%p for pointers.
The type of
char*, and so
cout<< thinks that you want to print a string.