为什么 C++ 不会打印 char 的内存地址,但会打印 int 或 bool?

2022-01-12 00:00:00 char c++ memory-address

可能重复:
为什么char数据的地址不显示?

这是代码和输出:

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;
}

输出:

a:0x28ac67的地址

Address of a:0x28ac67

b的地址:0x28ac66

Address of b:0x28ac66

c:0x28ac60的地址

Address of c:0x28ac60

d:0x28ac5c的地址

Address of d:0x28ac5c

e的地址:

我的问题是:char的内存地址在哪里?为什么不打印?

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

谢谢.

推荐答案

我怀疑 ostream::operatorchar * 的版本ostream::operator<<需要一个以 NUL 结尾的 C 字符串 - 并且您只传递一个字符的地址,所以您在这里拥有的是未定义的行为.您应该将地址转换为 void * 以使其打印您期望的内容:

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;

相关文章