-1

Possible Duplicate:
Why is address of char data not displayed?

I was experimenting with ampersand operator and got stuck at this program :

#include<iostream>
using namespace std;

int main() {
    char i='a';
    cout<<&i;
    return 1;
}

I was expecting the address of variable i as the output but instead the output came as the value of variable i itself.

Can anybody explain what just happened? Thanx in advance.

Community
  • 1
  • 1
Maverick Snyder
  • 31
  • 1
  • 1
  • 6

1 Answers1

4

That's because cout::operator<< has an overload for const char*. You'll need an explicit cast to print the address:

cout<<static_cast<void*>(&i);

This will call the overload with void* as parameter, which is the one used to print addresses.

Also note that your code runs into undefined behavior. You only have a single char there, and the overload expects a null-terminated C-string.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • I disagree about that the behavior is undefined. The shift operator behaves exactly as it is documented, it's the data that is corrupted :) – StoryTeller - Unslander Monica Dec 09 '12 at 15:27
  • @DimaRudnik there's no shift operator. – Luchian Grigore Dec 09 '12 at 15:27
  • Isn't that what the operator is called, shift left? – StoryTeller - Unslander Monica Dec 09 '12 at 15:29
  • @DimaRudnik it's not shifting bits, is it? I call it the stream operator, but come to think of it, I'm not sure that's the name. – Luchian Grigore Dec 09 '12 at 15:32
  • @DimaRudnik you're right, it's called the left shift operator. My bad :). The behavior is undefined because `cout` will continue printing until it finds a `'\0'`, but you only own the first `char`. Reading the next ones is illegal. – Luchian Grigore Dec 09 '12 at 15:36
  • For streams it's typically called the stream insertion operator; it has zilch to do with bit shifting. The behavior is undefined the instance that `std::ostream::operator<<(const char *)` attempts to access the character after `a` in `&i` (and this attempted access is exactly what will happen). – David Hammen Dec 09 '12 at 15:55