为什么C ++不打印char的内存地址,但打印int或bool? [英] Why C++ would not print the memory address of a char but will print int or bool?

查看:198
本文介绍了为什么C ++不打印char的内存地址,但打印int或bool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么不显示字符数据的地址?

下面是代码和输出:

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?

谢谢。

推荐答案

我怀疑重载 - char * 版本 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;

这篇关于为什么C ++不打印char的内存地址,但打印int或bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆