C语言 C 中的 LinkedList Struct Typedef
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18582205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LinkedList Struct Typedef in C
提问by oCodaa
I am try to build a basic linked list in C. I seem to get an error for this code:
我正在尝试用 C 构建一个基本的链表。我似乎收到此代码的错误:
typedef struct
{
char letter;
int number;
list_t *next;
}list_t;
char letters[] = {"ABCDEFGH"};
list_t openGame, ruyLopez;
openGame.letter = letters[4];
openGame.number = 4;
openGame.next = &ruyLopez;
ruyLopez.letter = letters[5];
ruyLopez.number = 4;
ruyLopez.next = NULL;
It won't accept my definition in the struct:
它不会在结构中接受我的定义:
list_t *next;
And for the same reason it won't accept:
出于同样的原因,它不会接受:
openGame.next = &ruyLopez;
回答by verbose
When you are using list_t *nextin your code, the compiler doesn't know what to do with list_t, as you haven't declared it yet. Try this:
当您list_t *next在代码中使用时,编译器不知道如何处理list_t,因为您还没有声明它。尝试这个:
typedef struct list {
char letter;
int number;
struct list *next;
} list;
As H2CO3 pointed out in the comments, using _tas an identifier suffix is not a great idea, so don't use list_t.
正如 H2CO3 在评论中指出的那样,使用_t作为标识符后缀并不是一个好主意,所以不要使用list_t.
回答by Farouq Jouti
why did you make it hard on yourself just set openGameand ruzeLopezas pointers and you wont have to use the &(this is the usual way to use linked lists , just don't forget to use ->to access members)
为什么你让自己很难,只是设置openGame和ruzeLopez作为指针,你不必使用&(这是使用链表的常用方法,只是不要忘记使用->访问成员)
try this code instead :
试试这个代码:
#include <stdlib.h>
#include <malloc.h>
typedef struct list
{
char letter;
int number;
struct list *next;
}list;
main(void)
{
char letters[] = "ABCDEFGH"; //what were the braces for ?
list *openGame, *ruyLopez;
openGame = ruyLopez = NULL;
openGame = malloc(sizeof(list));
ruyLopez = malloc(sizeof(list));
openGame->letter = letters[4];
openGame->number = 4;
openGame->next = ruyLopez;
ruyLopez->letter = letters[5];
ruyLopez->number = 5;
ruyLopez->next = NULL;
}
回答by bpmason1
Here is a working example without the risk of memory leaks from using malloc to create your structures.
这是一个工作示例,没有使用 malloc 创建结构时内存泄漏的风险。
#include <stdlib.h>
typedef struct _list
{
char letter;
int number;
struct _list *next;
} list_type;
int main(void)
{
char letters[] = "ABCDEFGH"; //what were the braces for ?
list_type openGame, ruyLopez;
openGame.letter = letters[4];
openGame.number = 4;
openGame.next = &ruyLopez;
ruyLopez.letter = letters[5];
ruyLopez.number = 5;
ruyLopez.next = NULL;
}

