首页 > 解决方案 > 为什么 C 输出中的自引用结构为空

问题描述

我想在 C 中创建一个结构,并且我希望它只有一个组件作为它的地址。

换句话说,我只是创建了一个组件自引用结构:

#include <stdio.h>
#include <string.h>
 
struct Books {
   struct Books *ptr; //* the only one component of this structure*//
};

int main( ) {
    struct Books book1;
    printf("%p\n", book1.ptr);
    
    return 0;
}

此脚本的输出为 - nil。

我的问题是 - 为什么?该脚本在计算机内存中创建了一个物理条目,其中记录了一个组件 structbook1。

现在我想查看这个结构的地址(或者换句话说,我想查看这个单组件结构的内容)。

一旦它物理存在,为什么它会给我输出 nill ?

标签: cpointersself-referenceconstruct

解决方案


如果您希望结构成员(或任何对象)具有特定值,则必须对其进行初始化或分配以具有该值。仅仅因为成员的类型是“指针struct Books”并不意味着它指向 struct Books它所在的位置或它具有任何其他特定值。

使用struct Books book1 = { &book1 };.

此外,应该为%p转换提供一个参数,因此请转换您传递的地址:。printfvoid *printf("%p\n", (void *) book1.ptr);


推荐阅读