【问题标题】:Displaying the Address of Chars显示字符的地址
【发布时间】:2014-11-09 08:00:17
【问题描述】:

所以我们在我的 C++ 类中创建了一个指向 char 的指针,指令如下:

对于每个声明,请确保:

  1. 将指针初始化为适当的地址值

  2. 显示指针的内容(将此值与指向的地址匹配)

  3. 显示指针指向的内容(将此值与原始内容匹配)

每当我尝试用 &a 显示 char a 的地址时,它只会输出存储在 char a 中的值而不是地址。当我用整数尝试这个时,它就像我想要的那样工作。

谁能告诉我我做错了什么?

#include <iostream>

using namespace std;

int main()
{

    // Question 1, Part I

    // (a)
    char a = 'A';

    char * pa = &a;

    //(b)
    cout << "Address of a = " << &a << endl;
    cout << "Contents of pa = " << pa << endl;

    //(c)
    cout << "Contents of a = "<< a << endl;
    cout << "What pa points to = "<< *pa << endl;

    return 0;
}

编辑并运行

【问题讨论】:

  • 转换为void*cout 对打印字符串的char* 有特殊处理。顺便说一句,您的代码表现出未定义的行为。

标签: c++ pointers reference char


【解决方案1】:

当你给 cout 一个指向 char 的指针时,它会认为它是一个空终止的 c 字符串。

将其重铸为空指针:

cout << "Address of a = " << static_cast<void*>(&a)  << endl;

标准保证4.10/2节中地址不变:

“指向 cv T 的指针”类型的纯右值,其中 T 是对象类型,可以是 转换为“指向 cv void 的指针”类型的纯右值。的结果 将指向对象类型的指针的非空指针值转换为 “指向 cv void 的指针”表示同一字节在内存中的地址 作为原始指针值。

这里解释一下pointer to char in output streams。这里解释了为什么要显示void* causes the value of the pointer

【讨论】:

    【解决方案2】:

    更改这些语句

    cout << "Address of a = " << &a << endl;
    cout << "Contents of pa = " << pa << endl;
    

    cout << "Address of a = " << ( void * )&a << endl;
    cout << "Contents of pa = " << ( void * )pa << endl;
    

    cout << "Address of a = " << reinterpret_cast<void *>( &a ) << endl;
    cout << "Contents of pa = " << reinterpret_cast<void *>( pa ) << endl;
    

    cout << "Address of a = " << static_cast<void *>( &a ) << endl;
    cout << "Contents of pa = " << static_cast<void *>( pa ) << endl;   
    

    所有三种变体都可以使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-08
      • 2023-01-26
      • 2019-06-09
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多