简体   繁体   English

C中的LinkedList Struct Typedef

[英]LinkedList Struct Typedef in C

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;

When you are using list_t *next in your code, the compiler doesn't know what to do with list_t , as you haven't declared it yet. 当您在代码中使用list_t *next时,编译器不知道如何处理list_t ,因为您还没有声明它。 Try this: 试试这个:

typedef struct list {
    char letter;
    int number;
    struct list *next;
} list;

As H2CO3 pointed out in the comments, using _t as an identifier suffix is not a great idea, so don't use list_t . 正如H2CO3在评论中指出的那样,使用_t作为标识符后缀并不是一个好主意,所以不要使用list_t

why did you make it hard on yourself just set openGame and ruzeLopez as 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) 你为什么要自己设置openGameruzeLopez作为指针并且你不必使用& (这是使用链表的常用方法,只是不要忘记使用->来访问成员)

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

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

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

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