char referencing

I have been working with pointers and using the & operator. But it does not seem to work with char variables.

e.g,

1
2
int telno = 1234567;
cout << "Reference of telno is " << &telno << endl;
This works.


But,
1
2
char sex = 'M';
cout << "reference of sex is " << &sex << endl;

doesn't work. I get garbage at the output

I can't figure out what the problem is.
The compilers converts &sex in a char* (C-style string), try this:
cout << "reference of sex is " << (void*)&sex << endl;
Last edited on
It works.
Could you just tell me what's happening exactly.
I didn't understand the part
The compilers converts &sex in a char* (C-style string)
In C strings were like this:
char* string = "Hello world";
and on C++ any char* is thought to be a C-style string for compatibily reasons.

so if you declare char sex;, sex is a char and &sex is a char* (pointer to a char). The output of a char* acts like a string.
A void* is a pointer to any type of variable so the output for that will be the reference and not the string translation of it.

I don't kow if I was very clear...
Read these, are better explained:
http://www.cplusplus.com/doc/tutorial/ntcs.html
http://www.cplusplus.com/doc/tutorial/pointers.html (Pointer initialization and void pointers paragraphs)
Yes, it is ostream trying to be smart.

Because C-strings were, as Bazzy said, char*, ostream thinks that when you tell it to output a char* you really mean you want it to output a C-string. But other pointer types don't have any other meaning, so ostream just outputs the pointer value.

Topic archived. No new replies allowed.