typedef struct Node{
int value;
struct node_t* next;
}node_t;
,一切工作正常,直到我把struct node_t* next
前int value
字段,然后我有很多垃圾值与工作那个结构。 这是关于错误的实现或代码中的其他内容?
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
ING整个想法是,你定义了一个新的类型,所以假设下面
typedef struct Node node;
然后申报node
类型的指针(注,再次node
是一种),
node *anode;
但你试图像
struct node *anode;
,它是错误的,因为没有为n在上面的代码中,struct node
,它是struct Node
。
代码中的另一个错误是,当编译器发现
struct node_t *next;
,因为如果其类型是可能这样
的结构之前,定义这已经是错node_t
类型不存在
typedef struct Node node_t
它会仍然是错误的,在node_t
类型使用struct
,因为编译器node_t
不是struct
这是一个新的TY pe,这又是struct Node
的简称。
在我的经验Typedefing结构比反正受益更多的麻烦。它不是这么难键入struct Something
,而不是仅仅Something
。它还具有更加明确的利益,所以如果另一程序员阅读你的代码,他们会立即知道Something
是一个struct
。
注:因为它被认为是不好的做法与_t
的后缀你自己定义的类型我特意更名为node
。这不一定是坏事,但多年来,我一直在与此工作,我开发了一些习惯,其中一个习惯是不使用_t
作为我自己定义类型的后缀。顺便说一句,只有在我的代码中存在,如果他们会提高可读性很多。否则,我只需使用struct
关键字的结构名称即可。
但是为什么它能以单向而不是另一种方式工作? – ead
@ead你的意思是?如果你想到你做到这一点,那根本没有意义。你在两个不同的地方为结构使用了不同的标签,它没有任何意义。一致性是非常重要的,即使你的代码是合理的,并且能够正确编译,它对自身也是不适应的,所以这是不好的做法。您应该深入阅读语法以了解什么是有效的和什么是无效的语法。我在[tag:c]中进行了5年左右的编程,但我仍然不知道所有的语法。我知道我并不是因为经常找到以前我不知道的东西。 –
您正在使用不存在的类型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;
在你的代码'node_t'是一个别名'结构Node'现在。希望有助于理解。 – GergelyPolonkai
请阅读更新后的答案,你现在明白了吗? –