我有以下代码,我正在尝试使其更具动态性和可重复使用。好吧,我有一个名为"学生和结构"列表的结构,其中包含所有添加的学生。我有一个函数" int addStudent(学生B,列表studentList({",并且我正在尝试将structs student和StudentList作为参数传递。但是问题是我做错了什么,我的列表并不包含所有添加的学生。它仅包含最后一个。你能帮我吗?
注意:我必须为"int addStudent(Student b, list StudentList)"
创建一个主体。不允许更改此功能的声明 ...这对我来说非常困难,我需要提出建议来处理...
预先感谢您!
#include <stdio.h>
#include <stdlib.h>
#define MAXSTRING 100
#define MAXLessonS 100
typedef enum genders{
female,
male
} genders;
typedef struct Student
{
char name[MAXSTRING];
char Surname[MAXSTRING];
enum genders gender;
int id;
char Lessons[MAXLessonS][MAXSTRING];
} Student;
typedef struct list
{
struct list * next;
struct Student * Student;
} list;
void printlist(list * StudentList)
{
list * current = StudentList;
while (current != NULL) {
printf("Student ID = %dn", current->Student->id);
printf("Student name = %sn", current->Student->name);
printf("Student Surname = %sn", current->Student->Surname);
printf("Student gender = %dn", current->Student->gender);
printf("Student Lesson = %sn", current->Student->Lessons);
current = current->next;
}
}
int main()
{
Student b={"name 1","Surname 1",male,22,{"Lesson 1"}};
Student c={"name 2","Surname 2",female,32,{"Lesson 2"}};
list* StudentList = NULL;
StudentList = malloc(sizeof(list));
StudentList->next = NULL;
//StudentList->next->next = NULL;
int x=addStudent(b,StudentList);
StudentList->next=NULL;
int xx=addStudent(c,StudentList);
printlist(StudentList);
return 0;
}
int addStudent(Student b, list StudentList){
//StudentList=malloc(sizeof(list));
StudentList.Student = &b;
//StudentList.next->next=NULL;
//free(StudentList);
return 1;
}
addStudent方法始终覆盖先前的节点。因此,您的列表仅包含1个节点。另外,要"存储"链接列表,您需要保留指向列表的头(第一个元素(的指针。
您有两个问题:
1(您将本地变量的地址添加到列表
2(您永远不会扩展列表,即始终包含一个元素
解决问题1(更改addStudent
功能:
int addStudent(Student* b, list* StudentList){
^^^ ^^^
Use a pointer
StudentList->Student = b;
^^^
Save the pointer
return 1;
}
并将其称为:
int x=addStudent(&b, StudentList);
^^
解决问题2(:
您需要malloc
新列表项目并将其插入当前列表。
但是,您当前的代码有点奇怪,因为您还会在main
中分配list
,但对此一无所获。相反,最好仅分配addStudent
函数中的list
项目。
一种简单的方法是:
// This function inserts new item in the front of the list
list* addStudent(Student* b, list* StudentList){
list* t;
t = malloc(sizeof(list));
if (!t) exit(1);
t->next = StudentList;
t->Student = b;
return t;
}
int main()
{
Student b={"name 1","Surname 1",male,22,{"Lesson 1"}};
Student c={"name 2","Surname 2",female,32,{"Lesson 2"}};
list* StudentList = NULL;
StudentList = addStudent(&b, StudentList);
StudentList = addStudent(&c, StudentList);
printlist(StudentList);
return 0;
}
使用一段时间用指针进入最后一个元素,然后在列表中创建您的新元素
void addStudent(Student *b, list *StudentList)
list *elem;
elem = StudentList;
while (elem->next)
elem = elem->next;
//now you can create your elem
elem->next = malloc(sizeof(list));
elem->next->student = b;
elem->next->next = NULL;