我有一个结构,我正在尝试打印其成员变量的地址。 当试图通过 &(f.c) 打印 char 成员变量的地址时,我没有得到他们的地址。
代码如下:
struct foo
{
char c;
short s;
void *p;
int i;
};
int main()
{
cout << "Size of foo: " << sizeof(foo) << endl;
foo f;
cout << "Address of c: " << reinterpret_cast<void*>(&f.c) << endl;
cout << "Address of c: " << &(f.c) << endl;
cout << "Address of s: " << reinterpret_cast<void*>(&f.s) << endl;
cout << "Address of s: " << &(f.s) << endl;
cout << "Address of p: " << reinterpret_cast<void*>(&f.p) << endl;
cout << "Address of p: " << &(f.p) << endl;
cout << "Address of i: " << reinterpret_cast<void*>(&f.i) << endl;
cout << "Address of i: " << &(f.i) << endl;
return 1;
}
输出
/pp/cplus/bas ]$ ./a.out
Size of foo: 12
Address of c: 0xffbfe680
Address of c: //----------- &(f.c). Why this is empty..
Address of s: 0xffbfe682
Address of s: 0xffbfe682
Address of p: 0xffbfe684
Address of p: 0xffbfe684
Address of i: 0xffbfe688
Address of i: 0xffbfe688
只是想知道为什么当我尝试通过 &(f.c) 访问它时它没有打印
使用gcc 3.4.6版本编译
最佳答案
cout
有一个 operator<<
char*
过载它将参数视为指向 C 字符串的指针,并尝试打印该 C 字符串中的所有字符,直到它到达 NUL (0) 字节。要解决此问题,您必须将地址转换为 void*
就像你在做每一行。
您刚刚体验过数组有时被视为二等数据类型的原因,因为它们在某些情况下会受到特殊对待(即 char
的数组在某些情况下会受到不同的对待,而在其他情况下则不会)。
Address of c:
是空的,因为这是您尝试打印 &f.c
指向的字符串时得到的结果.正如 dark_charlie 所指出的,使用未初始化的变量是未定义的行为,因此从技术上讲任何事情都有可能发生,但前者可能是对您所看到的情况的解释(尽管我们只能猜测)。
关于c++ - 访问结构的char成员变量地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9426375/