PIG443
PIG443

Reputation: 91

Build a struct with a struct inside

typedef struct Course {
char *CourseID;
char *CourseName;
struct Course* next;
} COURSE; 

typedef struct Student{
int ID;
struct Student* next
}STUDENT; 

I want to build a list of courses and then a list of students with the following each student has an ID and some courses from the courses list and a grade of each course. but how can I make that declaration inside the STUDENT struct? I cant understand that

For example Student: 3049583222 Course: Biology (from course list) grade: 30

and so on, every student could have all courses from the list.

Upvotes: 0

Views: 79

Answers (2)

A.R.C.
A.R.C.

Reputation: 920

My idea:

  • Linked List of Students.
  • Every student has a linked list of its courses with the grade.
  • The linked list elements have a pointer to the detailed course description.
// Description of a course
typedef struct Course {
char *CourseID;
char *CourseName;
} COURSE; 


// Struct to hold the students grade, as a linked list to generate a list of all courses the student has.
typedef struct coursesTaken {
    int grade;
    COURSE* courseDescription;
    struct coursesTaken* nextCourse;
} COURSES_TAKEN;


// The student with ID and pointer to his first course.
typedef struct Student{
int ID;
COURSES_TAKEN* firstCourse;
struct Student* next;
}STUDENT;

Upvotes: 1

IrAM
IrAM

Reputation: 1738

There can be multiple ways to do that, below shown are two approaches.

You can pick one and build on it.

typedef struct Course {
    char *CourseID;
    char *CourseName;
    struct Course* next;
} COURSE; 

typedef struct Student{
    int ID;
}STUDENT;

//approach 1
#define NIDS 10
#define NCOURSES 20

typedef struct Student_Course_1{
    STUDENT STU_ID[NIDS];           /* to store list of student ids */
    COURSE STU_Courses[NCOURSES];   /* to store list of courses    */
}COURSES_OF_STUDENT_1;

//approach 2

typedef struct Student_Course_2{
    STUDENT STU_ID;
    COURSE STU_Courses;
}COURSES_OF_STUDENT_2;


int main()
{
    COURSES_OF_STUDENT_1 cs1;       /* this has list of students and courses inside it */
    COURSES_OF_STUDENT_2 cs2[NIDS]; /* you can use NIDS list of students and courses info with this */
    
    return 0;
}

Upvotes: 1

Related Questions