【问题标题】:Why C++ would not print the memory address of a char but will print int or bool? [duplicate]为什么 C++ 不会打印 char 的内存地址,但会打印 int 或 bool? [复制]
【发布时间】:2012-11-23 20:17:36
【问题描述】:

可能重复:
Why is address of char data not displayed?

这是代码和输出:

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的地址

b的地址:0x28ac66

c:0x28ac60的地址

d:0x28ac5c的地址

e的地址:

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

谢谢。

【问题讨论】:

  • 好奇,你用的是什么编译器?
  • 你被 c++ 太聪明了一半搞砸了。 Plain ole c printf 没有这个问题,因为它不会尝试从参数的类型中推断出正确的格式。

标签: c++ char memory-address


【解决方案1】:

C/C++ 中的字符串可以用char* 表示,与&amp;e 的类型相同。所以编译器认为你正在尝试打印一个字符串。如果你想打印地址,你可以投到void*

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

【讨论】:

    【解决方案2】:

    我怀疑ostream::operator&lt;&lt; 的重载到char * 版本需要一个以NUL 结尾的C 字符串——而你只传递了一个字符的地址,所以你在这里看到的是未定义的行为。您应该将地址转换为 void * 以使其打印您期望的内容:

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

    【讨论】:

    • ( void * ) 是做什么的,能否给一个学习的来源(链接或搜索关键字)?
    • @KorayTugay 这是一个类型转换,请使用 Google。 (只是好奇:你知道static_cast&lt;void *&gt; 是做什么的,但不知道(void *) 是什么意思?)
    • 不,我也不知道。你的看起来更容易一些,所以我决定问你。
    • 所以你将 e 的地址转换为指针?但为什么无效?我会做一些搜索,希望能理解。
    • @KorayTugay 哦,我明白了 :) 我的逻辑完全相反。
    【解决方案3】:

    查看之前提出的这个问题:Why is address of char data not displayed?

    此外,如果您使用printf("Address of e: %p \n", &amp;e);,也可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多