Pergunta

I am attempting to create a Linked List using C (NOT C++). The Linked List is initialized through the function llinit() which should return a list struct. However, when I compile the code I get an error stating "error: invalid initializer" in the lltester.c file. Why is this?

This is the function used to initialize the linked list in my llist.c file:

list llinit()
{
    list* ll = malloc(sizeof(list));
    ll->head = NULL;
    ll->tail = NULL;
    return *ll;
}

This is the list struct in my llist.h file:

typedef struct {
    node *head;
    node *tail;
} list;

This is my main function in my lltester.c file where I attempt to initialize the list:

int main()
{
    list myList= llinit(); //This is the line where the error occurs on!

    return 0;
}
Foi útil?

Solução

Your code is leaking memory, since it's allocating the list with malloc() then returning that structure's content by value.

if you want to have a function that returns an empty list by value, you should do just that:

list llinit()
{
    list ll;
    ll.head = NULL;
    ll.tail = NULL;

    return ll;
}

The above is just fine, there's no risk of the value "disappearing" due to it going out of scope, this is just as safe as e.g. a function returning a local int value. The return value (all of it!) is copied to the caller's memory as needed.

It's then trivial for the caller to decide whether or not the node should be on the heap or not.

UPDATE: Here is the code on ideone, it really does compile and does not generate an error for the assignment in main().

Outras dicas

you have to declare the structure as

typedef struct _list{
list* head;  /* could have been struct node* as well */
list* tail;

} list;

Also the list is your custom struture. And the llPushBack() is not a bember of your structure.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top