在C语言中,如何在列表的末尾追加一个结构节点?

kb5ga3dv  于 2022-12-03  发布在  其他
关注(0)|答案(1)|浏览(118)
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"));
}

我想在列表的末尾追加一个新的struct节点,但是当我尝试运行main时,我得到了一个错误(分段错误)。
有人能帮我吗?:-)
我想问题可能是我在main中用NULL初始化了列表,但是我不知道我需要做什么修改,以便append-function可以处理它。

beq87vna

beq87vna1#

您有几个错误:

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

您可以在此处malloc一个已错位的对象:

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

而主要的问题是,你从来没有在append函数中连接头部(list)。
您的代码正在运行:

#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"));
}

请下次提供可编译的代码段。

相关问题