Prasanna Thapa Prasanna Thapa - 2 years ago 57
C++ Question

Printing just the pointer identifier in c++


int main()
char *cptr = new char('4');
char x = 0;
char *cptr1 = &x;
return 0;

why it prints cptr as 45(then some random character)
output be like 45P;
and it doesent print cprt1?

Answer Source

To print the contents of a pointer, you need to cast it to a void*:

std::cout << "Address stored in cptr is " << static_cast<void*>(cptr) << '\n';

If you don't do the cast, a pointer to char (i.e. char*) will be considered a pointer to a null-terminated byte string. I.e. a C-style string with a zero to mark the end of the string. Since your cptr pointer isn't actuall pointing to a "string" but rather a single character without a string terminator, that will cause the output operator << to go out of bounds in its search for the terminator, which leads to undefined behavior.

It actually works as intended with cptr1 since it points to a single character with the value 0 (the character '\0') which is the terminator, so it's a string of length zero, which is why nothing is printed for it.

If you want to print the character pointed to by e.g. cptr then you need to dereference the pointer:

std::cout << "The character pointed to by cptr is '" << *cptr << "'\n";

This will not really work for cptr1 since the character with value 0 is not printable. You have to cast it to an int to display its value:

std::cout << "The value integer pointed to by cptr1 is " << static_cast<int>(*cptr1) << '\n';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download