gpt4 book ai didi

c - 添加详细链接结构

转载 作者:行者123 更新时间:2023-11-30 16:44:55 24 4
gpt4 key购买 nike

我写了这段代码:(上面的结构和下面的函数)

list * add_student(slist * students, char * name, int id) {
slist * temp, * adder;

if (!(adder = (slist * )
malloc(sizeof(slist)))) exit(1);

student * data;

if (!(data = (student * )
malloc(sizeof(student)))) exit(1);

data - > name = name;
data - > id = id;
data - > courses = NULL;
adder - > info = data;
adder - > next = NULL;

if (!students) {
return adder;
}

for (temp = students; temp - > next; temp = temp - > next);
temp - > next = adder;
return students;
}

结构是:

typedef struct course {
char *title;
int number;
struct slist *students;
} course;

typedef struct slist {
student *info;
struct slist *next;
} slist;

typedef struct clist {
course *info;
struct clist *next;
} clist;

第一个函数应该将学生添加到学生列表中。它添加了学生,但如果我尝试添加另一个学生,则该名称将替换第一个学生的名称(仅名称而不是号码)。

我在代码中找不到错误,非常感谢您的帮助。

谢谢。

最佳答案

为名称分配内存并从名称参数中复制它:

list * add_student(slist * students, char * name, int id) {
slist * temp, * adder;
if (!(adder = (slist * ) malloc(sizeof(slist)))) exit(1);
student * data;
if (!(data = (student * ) malloc(sizeof(student)))) exit(1);
if (!(data->name = (char * ) malloc(sizeof(char) * (strlen(name)+1)))) exit(1);
strcpy(data->name, name);
data->id = id;
data->courses = NULL;
adder->info = data;
adder->next = NULL;
if (!students) {
return adder;
}
for (temp = students; temp - > next; temp = temp - > next);
temp - > next = adder;
return students;
}

关于c - 添加详细链接结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44312712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com