[英]Proper way to print address of character array
So, I have been digging into character array's lately, and I am trying to print the address of each element of a character array.所以,我最近一直在研究字符数组,我试图打印字符数组每个元素的地址。
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;
}
The code above gives me the following output:上面的代码给了我以下 output:
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]<<" ";
^
I am not comfortable about the output of (void*)a[i]
.我对
(void*)a[i]
的 output 感到不舒服。 Shouldn't the character addresses be 1 byte apart.字符地址不应该相隔 1 个字节。 I am seeing
0x69
followed by 0x63
and then by 0x65
.我看到
0x69
后跟0x63
,然后是0x65
。 Is there a reason for that.有没有原因。 And is there a relationship between the address representation and the warning sign that it is showing.
地址表示和它所显示的警告标志之间是否存在关系。
I am trying to print the address of each element of a character array
我正在尝试打印字符数组的每个元素的地址
(void*)a[i]
is converting the element (the char
) itself to void*
, not the address of the element. (void*)a[i]
将元素( char
)本身转换为void*
,而不是元素的地址。
You should get the address of each element as:你应该得到每个元素的地址:
cout<<(void*)&a[i]<<" ";
// ^
Or better to use static_cast
.或者更好地使用
static_cast
。
cout<<static_cast<void*>(&a[i])<<" ";
Your print value casted to void*
, to print address, you need您的打印值转换为
void*
,打印地址,您需要
cout<< static_cast<void*>(&a[i])<<" ";
Currently, you are not getting the addresses.目前,您没有获得地址。 You are casting the ASCII values of the characters to a
void*
instead.您正在将字符的 ASCII 值转换为
void*
。 This is why the values are not correct.这就是为什么值不正确的原因。
What you want to do is use a static_cast
and get the address of the element &a[i]
:您要做的是使用
static_cast
并获取元素&a[i]
的地址:
cout << static_cast<void*> (&a[i]) << " ";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.