Characters on the heap

So I'm doing a bit of experimenting to see just how memory is arranged on the heap. However, when I allocate single characters on the heap, and try to view their address, I get strange characters. Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;

int main()
{
    char *first = new char;
    char *second = new char;
    cout << "First is located on the heap at " << first << endl;
    cout << "Second is located on the heap at" << second << endl;
    return 0;
}
Last edited on
ostream's << operator treats char pointers special. It doesn't print the address, but rather assumes the address points to string data and tries to print it.

It's what makes this possible:
1
2
const char* foo = "a string";
cout << foo; // <- prints "a string" and not the actual pointer 


If you want to print the address, you'll have to cast to a different pointer type... like void*:

 
cout << "First is located on the heap at " << (void*)first << endl;
OK that makes sense. Thanks!
Topic archived. No new replies allowed.