访问结构的char成员变量地址

Dre*_*eer 1 c++ memory-management

我有一个结构,我试图打印其成员变量的地址.当试图通过&(fc)打印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;
}
Run Code Online (Sandbox Code Playgroud)

产量

/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
Run Code Online (Sandbox Code Playgroud)

只是想知道为什么它不打印当我试图通过&(fc)访问它

使用gcc版本3.4.6编译

Set*_*gie 9

cout有一个operator<<重载char*,它将参数视为指向C字符串的指针,并尝试打印该C字符串中的所有字符,直到它到达NUL(0)字节.要解决此问题,您必须将地址转换为void*您正在执行的每个其他行.

您刚刚经历过数组有时被视为二级数据类型的原因,因为它们在某些情况下被特殊处理(即char某些事物对数组的处理方式不同,而其他情况则不同).

Address of c:是空的,因为这是当你尝试打印指向的字符串时得到的&f.c.正如dark_charlie指出的那样,使用未初始化的变量是未定义的行为,所以从技术上讲任何事情都可能发生,但前者可能是你所看到的解释(尽管我们只能猜测).