Trying to make linkedlist in C

后端 未结 4 908
余生分开走
余生分开走 2021-01-27 19:43

I am trying to make a struct in C that is a linked list. I am not really sure what is going wrong though. My errors are:

linked.c:6:2: error: unknown type name         


        
4条回答
  •  时光取名叫无心
    2021-01-27 20:37

    The C compiler doesn't have a complete typedef of linkedList before you attempt to use it in your struct. You have a couple of options:

    typedef struct linkedList
    {
        int first;
        struct linkedList* rest;
    } linkedList;
    

    Or:

    typedef struct linkedList linkedList;  // C allows this forward declaration
    
    struct linkedList
    {
        int first;
        linkedList* rest;
    };
    

    This is your starting point.

    Additional problems include but are not limited to:

    • Your makeList function refers to variable first but it doesn't appear to be defined anywhere.
    • ll->rest = newL; assigned a type linkedList to a pointer to linkedList (linkedList *) you can't assign a value to a pointer-to-value. The compiler error message linked.c:43:13:... states this. It would need to be ll->rest = &newL;... HOWEVER...
    • newL is LOCAL to the function addToList, so you can't assign it's address to a persistent list item since it will go out of scope when the code leaves that block.
    • In addToList you are assigning pointer to integer to a variable that holds pointer to linkedList, e.g., second.rest = &c;.

提交回复
热议问题