Reputation: 1680
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:
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]
. Shouldn't the character addresses be 1 byte apart. I am seeing 0x69
followed by 0x63
and then by 0x65
. Is there a reason for that. And is there a relationship between the address representation and the warning sign that it is showing.
Upvotes: 1
Views: 53
Reputation: 172864
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.
You should get the address of each element as:
cout<<(void*)&a[i]<<" ";
// ^
Or better to use static_cast
.
cout<<static_cast<void*>(&a[i])<<" ";
Upvotes: 1
Reputation: 3187
Currently, you are not getting the addresses. You are casting the ASCII values of the characters to a void*
instead. 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]
:
cout << static_cast<void*> (&a[i]) << " ";
Upvotes: 1
Reputation: 217085
Your print value casted to void*
, to print address, you need
cout<< static_cast<void*>(&a[i])<<" ";
Upvotes: 1