I have the following code and I am trying to make it more dynamic and reusable. Well, I have a struct named Student and struct list, which contains all the added students. I have a function "int addStudent(Student b, list StudentList){", and I am trying to pass the structs Student and StudentList as parameters. But the problem is that I am doing something wrong and my list does not contains all the Students added. It contains only the last one. Can you help me?
NOTE: I have to create a body for the "int addStudent(Student b, list StudentList)". It is not permitted to change the declaration of this function ... this is very difficult for me and I need suggestions to work on ...
thank you in advance!
#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;: overwrites the pointer with the last one (c)...addStudentas it differs from how you're using it.