【问题标题】:Proper way to print address of character array打印字符数组地址的正确方法
【发布时间】:2020-06-17 08:06:59
【问题描述】:

所以,我最近一直在研究字符数组,我正在尝试打印字符数组中每个元素的地址。

char a[4] = {'i','c','e','\0'};
for(int i = 0; i < 3; ++i){
  cout<<(void*)a[i]<<" ";
  cout<<&a[i]<<" ";
  cout<<a[i]<<endl;
 }

上面的代码给了我以下输出:

0x69 ice i
0x63 ce c
0x65 e e
test.cpp: In function ‘int main()’:
test.cpp:29:23: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
       cout<<(void*)a[i]<<" ";
                       ^

我对@9​​87654323@ 的输出感到不舒服。字符地址不应该相隔 1 个字节。我看到0x69,然后是0x63,然后是0x65。有没有原因。地址表示和它所显示的警告标志之间是否存在关系。

【问题讨论】:

    标签: c++ arrays character


    【解决方案1】:

    我正在尝试打印字符数组中每个元素的地址

    (void*)a[i] 将元素(char)本身转换为void*,而不是元素的地址。

    你应该得到每个元素的地址:

    cout<<(void*)&a[i]<<" ";
    //           ^
    

    或者最好使用static_cast

    cout<<static_cast<void*>(&a[i])<<" ";
    

    【讨论】:

      【解决方案2】:

      你的打印值转换为void*,打印地址,你需要

      cout<< static_cast<void*>(&a[i])<<" ";
      

      【讨论】:

        【解决方案3】:

        目前,您没有获得地址。您正在将字符的 ASCII 值转换为 void*。这就是值不正确的原因。

        您要做的是使用static_cast 并获取元素&amp;a[i] 的地址:

        cout << static_cast<void*> (&a[i]) << " ";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-02
          • 2023-02-07
          • 1970-01-01
          • 2013-04-27
          相关资源
          最近更新 更多