为什么我不能获取其中元素a
和的地址?c
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;
}
输出:
address of a:
address of b: 0x61620d70c6c2
address of c:
address of d: 0x61620d70c6c8
编译自:
g++ main.cpp -o main -std=c++23
这是因为这些成员是字符。获取地址时,您将传递一个
char*
。ostream
有一个重载operator<<
,将 a 视为char*
以 NUL 结尾的 C 字符串,打印字符而不是地址。要打印地址,您可以将 转换char*
为void*
。