[英]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.