【问题标题】:Linked list Implementation in C with structure链表在 C 中的结构实现
【发布时间】:2016-11-26 02:05:30
【问题描述】:

我使用这个结构作为链表:

 typedef struct Node{
       int value;
       struct node_t* next;

 }node_t;

一切正常,直到我将struct node_t* next 放在int value 字段之前,然后我有很多垃圾值与该结构一起使用。 是关于错误的实现还是代码中的其他内容?

【问题讨论】:

  • 在您的代码中,node_t 现在是 struct Node 的别名。希望有助于理解。
  • 请阅读更新后的答案,你现在明白了吗?

标签: c struct linked-list structure


【解决方案1】:

您正在调用您的结构Node 并定义node_t 类型。然后您使用node_t,就好像它是结构的名称而不是类型。

试试这个

typedef struct node {
    int value;
    struct node *next;
} Node;

或者

typedef struct node Node;
struct node {
    int value;
    Node *node;
};

如果你叫它struct Node,那么

struct Node {
    int value;
    /* The compiler doesn't know what `struct Node' is yet */
    struct Node *next;
    /* But you can always declare pointers, even of types the compiler
     * doesn't know everything about. Because the size of a pointer
     * does not depend on the type of the pointee.
     */
};

在您的示例中,情况更糟。你typedefed 了一些编译器理解的新类型,要使用它你不能使用structtypedefing 背后的整个想法是你定义了一个新类型,所以假设如下

typedef struct Node node;

然后声明node 类型的指针(注意,再次node IS A TYPE),

node *anode;

但你尝试过类似

struct node *anode;

这是错误的,因为上面的代码中没有struct node,而是struct Node

您的代码中的另一个错误是,当编译器找到 node_t 类型时,

struct node_t *next;

这已经是错误的,因为如果类型是在结构之前定义的,那么可能像这样

typedef struct Node node_t

node_t 类型上使用struct 仍然是错误的,因为对于编译器而言,node_t 不是struct,它是一个新类型,而它又只是struct Node 的别名.

根据我的经验,类型定义结构是麻烦多于好处。输入struct Something 而不仅仅是Something 并不难。它还具有更明确的好处,因此如果其他程序员阅读您的代码,他们将立即知道Somethingstruct

注意:我故意将名称更改为 node,因为在您自己定义的类型后面加上 _t 被认为是不好的做法。这不一定是一件坏事,但多年来我一直在使用它,我养成了一些习惯,其中一个习惯是不要使用_t 作为我自己定义的类型的后缀。顺便说一句,如果它们会大大提高可读性,那么它们仅存在于我的代码中。否则,我只需使用带有 struct 关键字的结构名称。

【讨论】:

  • @ead 你是什么意思?如果您考虑一下自己的做法,那根本没有意义。您在两个不同的地方为结构使用了不同的标签,这没有意义。一致性非常重要,即使您的代码有意义并且可以正确编译,它也与自身不一致,因此这是不好的做法。您应该深入阅读语法以了解什么是有效的,什么是无效的。我已经在c 编程了 5 年左右,但我仍然不知道所有的语法。我知道我不知道,因为我经常发现以前不知道的东西。
【解决方案2】:

您正在使用不存在的类型 node_t。该类型不存在,因为类型 struct Node 甚至不完整并且您正在使用它的别名。将typedefs 与结构一起使用时要记住的另一件事不要将结构关键字与别名一起使用 例如。

/* This is correct */
typedef struct Node
{
    int x;
    struct Node *next;
} node_t;

/* while these are incorrect */

/* Prefixing struct keyword to a typedef'ed type */
struct node_t *listhead;

/* The type is inclomplete and you are using an alias of the type
   which doesn't even exist */
typedef struct Node
{
    int x;
    node_t *next;
};

【讨论】:

    【解决方案3】:

    您正在尝试创建一个指向您尚未创建的结构的指针。所以,应该是,

    typedef struct Node{
    int value;
    struct Node* next;
    }node_t;
    

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 2013-02-13
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2011-10-25
      相关资源
      最近更新 更多