Why can't I take the address of the elements a
and c
in this struct
?
#include <iostream>
struct Silly {
char a;
unsigned short b;
char c;
double d;
};
int main() {
auto p_silly = new Silly[2];
std::cout << "address of a: " << &(p_silly[0].a) << std::endl;
std::cout << "address of b: " << &(p_silly[0].b) << std::endl;
std::cout << "address of c: " << &(p_silly[0].c) << std::endl;
std::cout << "address of d: " << &(p_silly[0].d) << std::endl;
delete[] p_silly;
}
The output:
address of a:
address of b: 0x61620d70c6c2
address of c:
address of d: 0x61620d70c6c8
Compiled with:
g++ main.cpp -o main -std=c++23
It's because those members are characters. When you take the address, you're passing a char*
. ostream
has an overloaded operator<<
that treats a char*
as a NUL-terminated C string, printing the characters instead of the address. To print the address, you can cast the char*
to void*
.