打印字符数组地址的正确方法
Proper way to print address of character array
所以,我最近一直在研究字符数组,我正在尝试打印字符数组的每个元素的地址。
char a[4] = {'i','c','e','[=10=]'};
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])<<" ";
您的打印值转换为void*
,要打印地址,您需要
cout<< static_cast<void*>(&a[i])<<" ";
目前,您没有获取地址。您正在将字符的 ASCII 值转换为 void*
。这就是值不正确的原因。
您要做的是使用 static_cast
并获取元素 &a[i]
:
的地址
cout << static_cast<void*> (&a[i]) << " ";
所以,我最近一直在研究字符数组,我正在尝试打印字符数组的每个元素的地址。
char a[4] = {'i','c','e','[=10=]'};
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])<<" ";
您的打印值转换为void*
,要打印地址,您需要
cout<< static_cast<void*>(&a[i])<<" ";
目前,您没有获取地址。您正在将字符的 ASCII 值转换为 void*
。这就是值不正确的原因。
您要做的是使用 static_cast
并获取元素 &a[i]
:
cout << static_cast<void*> (&a[i]) << " ";