Why C++ would not print the memory address of a ch

2019-04-04 18:56发布

问题:

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

Here is the code and the output:

int main(int argc, char** argv) {

    bool a;
    bool b;

    cout<<"Address of a:"<<&a<<endl;
    cout<<"Address of b:"<<&b<<endl;

    int c;
    int d;

    cout<<"Address of c:"<<&c<<endl;
    cout<<"Address of d:"<<&d<<endl;

    char e;    
    cout<<"Address of e:"<<&e<<endl;

    return 0;
}

The output:

Address of a:0x28ac67

Address of b:0x28ac66

Address of c:0x28ac60

Address of d:0x28ac5c

Address of e:

My question is: Where is the memory address of the char? And why is it not printed?

Thank you.

回答1:

I suspect that the overloaded-to-char * version of ostream::operator<< expects a NUL-terminated C string - and you're passing it only the address of one character, so what you have here is undefined behavior. You should cast the address to a void * to make it print what you expect:

cout<<"Address of e:"<< static_cast<void *>(&e) <<endl;


回答2:

Strings in C/C++ can be represented by char*, the same type as &e. So the compiler thinks you're trying to print a string. If you want to print the address, you could cast to void*.

std::cout << static_cast<void *>(&e) << std::endl;


回答3:

Check out this previously asked question: Why is address of char data not displayed?

Also, if you utilize printf("Address of e: %p \n", &e); that will work as well.