flw*_*lwn 4 c struct structure linked-list
我使用此结构作为链表:
typedef struct Node{
int value;
struct node_t* next;
}node_t;
Run Code Online (Sandbox Code Playgroud)
一切工作都很好,直到我将其放在字段struct node_t* next之前为止int value,然后我在该结构上有很多垃圾值。是关于错误的实现还是代码中的其他内容?
您正在调用结构Node并定义node_t类型。然后,您使用的node_t好像它是结构的名称而不是类型。
尝试这个
typedef struct node {
int value;
struct node *next;
} Node;
Run Code Online (Sandbox Code Playgroud)
要么
typedef struct node Node;
struct node {
int value;
Node *node;
};
Run Code Online (Sandbox Code Playgroud)
如果你叫它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.
*/
};
Run Code Online (Sandbox Code Playgroud)
在您的示例中,情况甚至更糟。typedef根据编译器的理解,您编辑的是一种新类型的东西,要使用它一定不要使用struct。typedefing 的整个想法是,您定义了一个新类型,因此假设以下内容
typedef struct Node node;
Run Code Online (Sandbox Code Playgroud)
然后声明一个类型的指针node(注意,再次node是IS TYPE),
node *anode;
Run Code Online (Sandbox Code Playgroud)
但您尝试过类似
struct node *anode;
Run Code Online (Sandbox Code Playgroud)
这是错误的,因为struct node上面的代码中没有struct Node。
您的代码中的另一个错误是,node_t当编译器找到该类型时,该类型不存在。
struct node_t *next;
Run Code Online (Sandbox Code Playgroud)
这已经是错误的,因为如果类型是在结构之前定义的,则可能像这样
typedef struct Node node_t
Run Code Online (Sandbox Code Playgroud)
struct在node_t类型上使用它仍然是错误的,因为对于编译器而言,node_t它不是struct一个新类型,而它又仅仅是struct Node。的别名。
从我的经验来看,类型定义结构总比麻烦多于收益。键入struct Something而不是很难Something。它还具有更明确的好处,因此,如果另一个程序员读取您的代码,他们将立即知道这Something是一个struct。
注意:我故意将名称更改为,node因为用来给自己定义的类型添加后缀是一种不好的做法_t。这不一定是一件坏事,但是多年来,我一直在养成一些习惯,其中一个习惯就是不要将_t其用作我自己定义的类型的后缀。顺便说一句,它们只会在我的代码中存在,如果它们可以大大提高可读性。否则,我仅将结构的名称与struct关键字一起使用。
| 归档时间: |
|
| 查看次数: |
340 次 |
| 最近记录: |