Home > Mobile >  How can I append a struct node at the end of a list in C?
How can I append a struct node at the end of a list in C?

Time:11-09

struct item {
    char name[32];
    struct item *next;
};

struct item *create_item(char *name) {
    struct item *result = malloc(sizeof(struct item));
    strcpy(result->name, name);
    result->next = NULL;
    return result;
}

int equals(char *a, char *b) {
    return strcmp(a, b) == 0;
}

void append(struct item **list, struct item *i){

    i = malloc(sizeof(struct item));
    struct item *last = *list;
    strcpy(i->name, i->name);
    i->next = NULL;

    if(*list == NULL){
        *list = i;
    }

    while(last->next != NULL) {
        last = last->next;
    }
    last->next = i;
}

int main(void) {
    struct item *list = NULL;
    append(&list, create_item("Dog"));
    append(&list, create_item("Cat"));
    append(&list, create_item("Bat"));
    assert(equals(list->next->next->name, "Bat"));
}

I would like to append a new struct node at the end of a list, but I get an error (segmentation fault) when I try to run main.

Can someone please help me? :-)

I think the problem might be that I am initializing the list with NULL in main, but I don't know what I need to change so the append-function can handle it.

CodePudding user response:

You have several errors:

demo.c: In function ‘append’:
demo.c:26:13: warning: passing argument 1 to ‘restrict’-qualified parameter aliases with argument 2 [-Wrestrict]
   26 |     strcpy(i->name, i->name);

You malloc an already malloced object here:

i = malloc(sizeof(struct item)); // choose a better name, 'i' sucks :)

And the main problem, you never connect the head (list) in the append function.

Your code working:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

struct item {
    char name[32];
    struct item *next;
};

struct item *create_item(const char *name) // const added
{
    struct item *result = malloc(sizeof(struct item));

    strcpy(result->name, name);
    result->next = NULL;
    return result;
}

int equals(char *a, char *b)
{
    return strcmp(a, b) == 0;
}

void append(struct item **list, struct item *item)
{
    if (*list == NULL)
    {
        *list = item;
        return;
    }

    struct item *next = *list;
    struct item *tail = NULL;

    while (next != NULL)
    {
        tail = next;
        next = next->next;
    }
    tail->next = item;
}

int main(void)
{
    struct item *list = NULL;

    append(&list, create_item("Dog"));
    append(&list, create_item("Cat"));
    append(&list, create_item("Bat"));
    assert(equals(list->next->next->name, "Bat"));
}

Please, next time provide a compilable snippet.

  • Related