因此,最近我一直在研究字符数组,并且正在尝试打印字符数组每个元素的地址。
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/