cout << and Addresses

Can anyone tell me where I'm going wrong here?

Basically trying to view the address inside of a pointer variable using cout, but it seems to be dereferencing the pointer whether I tell it to or not?

Was trying to debug some code that reads data in an OS's memory and noticed I wasn't seeing what I expected in my displays, So I rendered it down to this example.

Anyone want to rub my nose in my error?

1
2
3
4
5
6
7

// cout Deref testing          
char x = 'A';  // Define x and put 'A' in it.                                 
char *y = &x;  // Define pointer to x and put address                         
cout << " y: "  << y  << "\n";  //  Expect to see an address but see 'A', why?                   
cout << " *y: " << *y << "\n";  // Expect to see 'A' and do.    
 


Results:

1
2
3
4

 y: A  
 *y: A 
you've just happened to use a char*, rather than a pointer to some other type, and char* is something of a special type which was used to represent strings in C before std::strings in C++, and as such has a series of overloads which change its behaviour, for example:

1
2
3
4
5
6
7
8
char* str = "some string"; // this is valid
int* i = 1234; // this not...
// you must allocate memory for the int* like so
int* j = new int;
*j = 1234;

std::cout << str; // prints the string, not the memory address of the pointer
std::cout << j; // prints the memory address of the pointer 
Last edited on
The proper way to display the contents of the char pointer, instead of the C-string that the pointer gets interpreted as:
1
2
3
4
5
// cout Deref testing          
char x = 'A';
char *y = &x;
cout << " y: "  << static_cast<void*>(y)  << "\n";  //Change type of y to avoid C-string overrides.
cout << " *y: " << *y << "\n";
more easy way:
cout << " y: " << &y << "\n"; // print address of y
http://www.cplusplus.com/articles/EN3hAqkS/
Moschops here is great at explaining things
Thanks everyone. Much appreciated.

Took me a bit to recognize the << is overloaded and is doc'ed in <ostream>, and that it wasn't cout behavior that was the issue.

Once I realized that char * behavior is designed to dereference, I go the idea, LOL!

I'm afraid I'm used to thinking in assembler, so having a compiler that does so much under the covers is going to make for a steep learning curve, LOL!
Topic archived. No new replies allowed.