为什么我不能记下元素的地址 a 和 c 在这个 struct ?
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* iostreams有一个重载,它将char*视为以NUL结尾的字符串(这是C传递它们的方式),而不是地址,并将其打印为字符串。
char*