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"));
}
我想在串列末尾追加一個新的結構節點,但是當我嘗試運行 main.js 時出現錯誤(分段錯誤)。
有人可以幫幫我嗎?:-)
我認為問題可能是我在 main 中使用 NULL 初始化串列,但我不知道我需要更改什么以便附加函式可以處理它。
uj5u.com熱心網友回復:
你有幾個錯誤:
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 :)
主要問題是,您永遠不會在函式中連接頭部(list) 。append
你的代碼作業:
#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"));
}
請下次提供可編譯的代碼段。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530233.html
標籤:C列表结构附加
