gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:53:24 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com