In reference to the code below: why does in one case we get the full string and in the other the address? Can someone please explain this?

char mary[] = "Mary";
char* aPtr = &mary[0];

int b = 5;
int* bPtr = &b;

cout << "aPtr value is " << aPtr << endl; // Prints "Mary"
cout << "bPtr value is " << bPtr << endl; // Prints address of integer b

Dani AI

Generated

Short answer in plain terms: the stream library treats character pointers as C-strings but treats other pointer types as plain addresses. noticed the behavior; the formal reason is that the iostreams overload operator<< for const char* and that overload writes characters until the terminating NUL, while the pointer overload formats the pointer value for other pointer types (see the operator<< reference below).

To print the address of a char* rather than the characters, cast it to a void pointer so the pointer overload is selected. This is clearer and safer than casting to an integer pointer. For example:

cout << static_cast<const void*>(p) << '\n';

(Prefer static_cast<const void*> to make intent explicit.)

Additional notes tied to the thread: was on the right track about casting but casting to int* is nonportable and semantically wrong. If the string came from a literal, prefer const char* or std::string to avoid undefined behavior when modifying data. Also remember that signed char* or unsigned char* do not match the const char* overload and will print as addresses, so pointer type matters for what operator<< selects.

Reference: basic_ostream::operator<< overloads

Recommended Answers

All 2 Replies

It works differently for char. It does not print the address, but it prints all
characters that the pointer is pointing to, until it reaches a null character.

You can reinterpret_cast your char pointer to an int pointer or void pointer to print out its address.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.