I do not get the address of a character when using &. Why?

Hello,
When I write: int x; cout << & x ; I get what is expected i.e. the address of that particular variable. However when I write: char y; cout << &y; I get 3 special characters rather than the regular address of variable y.
When I initialize y with some character e.g.: y = 'a'; amd then write: cout << &y; the console displays: a. Can someone please help me before I go nuts?
char* is a special case because C-style strings and string literals are cast to char*. Therefore, couting a char* outputs the string data and not the pointer.

Example:

1
2
3
4
5
6
7
char str[] = "A string";
char ch = '!';

cout << str;  // this is couting a char*
cout << "foobar";  // so is this!
cout << &ch;  // this is also couting a char*


Obviously you don't want the first two of those to print an address. Yet the compiler can't tell the difference between any of them, so it has to treat them all the same way.

To get around it, you can cast your char* to something else:

 
cout << (void*)&ch; // now it will print an address 
Thank you Disch. After much study prompted by your kind reply, I suppose the lack of analogy between char type and e.g. int type results from the fact that int is a fundamental type and char isn't. Still I think this should be mentioned in the chapter about pointers in the tutorial of cplusplus in order not to mislead noobs like I.
A char is a fundamental type. If you are going to blame anything...blame C. :P
Topic archived. No new replies allowed.