繁体   English   中英

链表在C中用结构实现

[英]Linked list Implementation in C with structure

我正在使用此结构作为链接列表:

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

 }node_t;

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

您正在调用结构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.
     */
};

在你的例子中,情况更糟。 typedef编的东西,是一种新型的编译器理解它,使用它,你不能使用struct typedef背后的整个想法是你定义了一个新类型,所以假设如下

typedef struct Node node;

然后声明一个node类型的指针( 注意,再次node是一个类型 ),

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的别名。

根据我的经验,Typedefing结构比无论如何更有麻烦。 并且输入struct Something而不仅仅是Something并不是那么难。 它还具有更明确的优点,因此如果另一个程序员读取您的代码,他们将立即知道Something是一个struct

注意 :我故意将名称更改为node因为用_t自己定义的类型后缀被认为是不好的做法。 这不一定是件坏事,但多年来我一直在研究这个问题,我养成了一些习惯,其中一个就是不使用_t作为我自己定义的类型的后缀。 顺便说一句,只有这样才能提高可读性。 否则,我只需使用struct关键字的结构名称。

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

/* 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;
};

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM