c++ - 正确打印字符数组地址的方法

标签 c++ arrays character

因此,最近我一直在研究字符数组,并且正在尝试打印字符数组每个元素的地址。

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]<<" ";
                       ^

我对(void*)a[i]的输出不满意。字符地址不应相隔1个字节。我看到的是0x69,接着是0x63,然后是0x65。是否有原因。地址表示形式和所显示的警告标志之间是否存在关系。

最佳答案

I am trying to print the address of each element of a character array


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

您应该获得每个元素的地址为:
cout<<(void*)&a[i]<<" ";
//           ^

或更好地使用static_cast
cout<<static_cast<void*>(&a[i])<<" ";

关于c++ - 正确打印字符数组地址的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62424298/

相关文章:

c++ - 解析一个非常简单的配置文件

C++ 和 box2d : userdata cast int to void*

c++ - 具有 const 不可复制元素的元组

java - Character.toUpperCase() 和 Character.toTitleCase() 有什么区别

python - 如何在wxpython中传递字符'素数?

java - Android 上可以使用哪些字符?

c++ - QT/SQLITE-数据库上的奇怪符号?

python - SQLite 跨具有重复分组行的多列进行 SELECT 查询

php - 将 HTML 表格数据转换为转置的二维数组

c - C 中包含结构的数组中的错误值