pointers and standard output

In the below program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
template <typename T, int nSize> // nSize is the expression parameter
class Buffer
{
private:
    // The expression parameter controls the side of the array
    T m_atBuffer[nSize];
 
public:
    T* GetBuffer() { return m_atBuffer; }
 
    T& operator[](int nIndex)
    {
        return m_atBuffer[nIndex];
    }
};

# Using templates, we might write something like this:
template <typename T, int nSize>
void PrintBufferString(Buffer<T, nSize> &rcBuf)
{
    std::cout << rcBuf.GetBuffer() << std::endl;
}

# This would allow us to do the following:
int main()
{
    // declare a char buffer
    Buffer<char, 10> cChar10Buffer;
 
    // copy a value into the buffer
    strcpy(cChar10Buffer.GetBuffer(), "Ten");
 
    // Print the value
    PrintBufferString(cChar10Buffer);
    return 0;
}

// prints:
Ten


The call to GetBuffer() seems to return a pointer to the char object. So why does this print what the actual char holds (in this case "Ten") rather than the address that it is pointing to?
So why does this print what the actual char holds (in this case "Ten") rather than the address that it is pointing to?

Because pointers to char are treated specially.
This behavior is inherited from C, where char arrays and by extension char pointers are used for text messages.

If you want to print the memory address, you could cast the pointer:

1
2
3
4
5
6
7
8
9
#include <iostream>

int main()
{
	const char *cp = "Hello, World!";

	std::cout << reinterpret_cast<const void *> (cp) << '\n';
	std::cout << cp << std::endl;
}
0x8048870
Hello, World!
Topic archived. No new replies allowed.