LinkedList Struct Typedef in C

后端 未结 3 613
生来不讨喜
生来不讨喜 2021-01-18 03:19

I am try to build a basic linked list in C. I seem to get an error for this code:

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


        
相关标签:
3条回答
  • 2021-01-18 03:43

    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. 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.

    0 讨论(0)
  • 2021-01-18 03:46

    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)

    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;
    }
    
    0 讨论(0)
  • 2021-01-18 03:55

    Here is a working example without the risk of memory leaks from using malloc to create your structures.

    #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;
    }
    
    0 讨论(0)
提交回复
热议问题