【发布时间】:2017-05-31 13:55:05
【问题描述】:
我有以下代码,我正在努力使其更具动态性和可重用性。 好吧,我有一个名为 Student 的结构和结构列表,其中包含所有添加的学生。我有一个函数“int addStudent(Student b,list StudentList){”,我试图将结构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 = %d\n", current->Student->id);
printf("Student name = %s\n", current->Student->name);
printf("Student Surname = %s\n", current->Student->Surname);
printf("Student gender = %d\n", current->Student->gender);
printf("Student Lesson = %s\n", 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;
}
【问题讨论】:
-
StudentList.Student = &b;:用最后一个(c)覆盖指针... -
您的列表只包含一个节点 - 同样令人惊讶的是,您没有收到有关
addStudent定义的警告/错误,因为它与您使用它的方式不同。 -
@Jean-François Fabre 我无法理解如何解决它......
-
@Chris Turner 我正在使用 Dev-C++ 编译器...而且我没有任何错误警告...
标签: c function struct linked-list parameter-passing