【问题标题】:Accessing char member variable address of a structure访问结构的 char 成员变量地址
【发布时间】:2012-02-24 06:26:28
【问题描述】:

我有一个结构,我正在尝试打印其成员变量的地址。 当试图通过 &(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 编译

【问题讨论】:

    标签: c++ memory-management


    【解决方案1】:

    coutoperator&lt;&lt; 有一个 operator&lt;&lt; 重载 char* 将参数视为指向 C 字符串的指针,并尝试打印该 C 字符串中的所有字符,直到它到达 NUL (0)字节。为了避免这种行为,您必须将地址转换为 void*,就像您每隔一行一样。

    您刚刚体验了数组有时被视为二等数据类型的原因,因为它们在某些情况下被特殊对待(即char 的数组被某些事物区别对待,而另一些事物则不同)。

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

    【讨论】:

      【解决方案2】:

      原因是没有重新解释强制转换 &(f.c) 是一个 char* 指针,它被 cout 视为字符串。因为你没有用任何东西填充 char,所以你调用了一个未定义的行为(即它可以打印任何东西)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-17
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        相关资源
        最近更新 更多