【问题标题】:Is it possible to create a struct inside the same uncreated struct?是否可以在同一个未创建的结构中创建一个结构?
【发布时间】:2018-07-23 12:42:26
【问题描述】:

以下声明可能吗?如果是这样,您如何访问结构内的元素?它可以编译,但我无法访问元素。

struct node
{
    int a;
    struct node *next;
};
struct node *node1;
int main()
{
    node1->a = 5; // I cannot perform this operation
    return 0;
}

【问题讨论】:

  • 这是一个非常常见和标准的单链表的典型结构布局。您可以像访问任何其他结构一样访问成员。
  • node * 可能更好地理解为在 struct 内创建一个指针。
  • “我无法访问元素”是什么意思?没有尝试访问您在此处显示的代码中的元素。请显示您尝试过的内容以及收到的错误消息。另见:minimal reproducible example
  • 顺便说一句,在 C++ 中你不需要写 struct node * 只需 node* 就可以了(在这方面它与 C 不同)。虽然理想情况下你会使用智能指针而不是原始指针
  • 事实上在 C++ 中你应该使用 containers 并将这个 struct 连接 留给学术界和糟糕的 C++ 面试官。

标签: c++ pointers object struct


【解决方案1】:

我认为您需要复习该语言的基础知识。因此,可能需要一个指向书单的链接:


解决您的问题:

在这里你定义了一个类型,即一个名为node的结构体,它包含一个int类型的对象和一个指向一个node类型的对象的指针 (struct node*):

struct node
{
    int a;
    struct node *next;
};

在这里你声明了一个类型为指向节点类型对象的指针的全局对象:

struct node *node1;

注意指针默认是无效的,也就是说,它们不会自动指向一个对象。

所以你有一个指针,但你实际上没有一个 节点类型的对象。 因此,您不允许取消引用指针。禁止访问指针当前恰好指向的(任意)内存位置。

int main()
{
    node1->a = 5; // It is forbidden to perform this operation
    return 0;
}

为了解决这个问题。你需要创建一个对象并让指针指向它。

例子:

int main() {
    node n; // create an object of type node
    node1 = &n; // Assign the address of the object n to the pointer
    node1->a = 5; // Now it's allowed to dereference the pointer
}

最后:

是否可以在同一个未创建的结构中创建结构?

您可以拥有一个包含指向相同类型对象的指针的类型。这对于实现递归数据结构(例如链表或树)很有用。

进一步阅读:

【讨论】:

    【解决方案2】:

    根据您的 MCVE,您没有创建节点,您有一个未初始化的指针。 node* next 似乎是您当前问题的一个红鲱鱼。

    struct node
    {
        int a;
        node *next; // seems to be a red herring to your current problem.
    };
    
    int main()
    {
        node node1; // <-- for this demo, create it on the stack
        node1.a = 5;
        return 0;
    }
    

    注意; node * 可能更好地理解为在 struct 中创建指向相同类型结构的指针(这是允许的),而不是“未创建结构中的结构”。

    【讨论】:

      【解决方案3】:

      您无法访问字段,因为您只创建了一个指向结构实例的指针,而不是最后一个。像这样访问元素是一种未定义的行为。为了使它正确,你应该写例如

      struct node *node1;
      int main()
      {
          node1 = new node();
          node1->a = 5; // now ok
          node1->next = new node(); // again, before this we had an unitialized ptr.
          return 0;
      }
      

      另一个问题是在这种情况下它不是一种非常有效的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-15
        • 1970-01-01
        相关资源
        最近更新 更多