Reputation: 261
I'm writing a database of students in C and I've defined two structures Student and Course which look like this:
typedef struct student Student;
typedef struct course Course;
struct course
{
char number[300];
char title[300];
char instructor[300];
char days[10];
char start[10];
char end[10];
char location[300];
};
struct student
{
char name[300];
int age;
Course course1;
Course course2;
};
Student *Data[30];
Course *Courses[30];
I'm having trouble displaying the students I create though. I just want to print out the name, age and two courses, but I'm having trouble accessing the elements of the course structure through the student one.
I've tried this:
printf("course1: %s\t%-40s%-30s\t%s\t%s-%s\t%s\n",
Data[i]->course1.number,
Data[i]->course1.title,
Data[i]->course1.instructor,
Data[i]->course1.days,
Data[i]->course1.start,
Data[i]->course1.end,
Data[i]->course1.location);
But of course that isn't working...
Upvotes: 2
Views: 222
Reputation: 7716
I've simplified your structs a bit as an instructional example. This might help you to understand how to access the data. Tweak/expand as necessary to suit your needs.
typedef struct student Student;
typedef struct course Course;
struct course {
char title[300];
};
struct student {
char name[300];
Course * course; // pointer to a course
};
Student students[30]; // preallocate 30 students
Course courses[30]; // preallocate 30 courses
Tester:
void main(void) {
// 1st course
strcpy(courses[0].title,"C Language 101");
// 1st Student
strcpy(students[0].name,"Charles");
// Assign 1st Student to course #1
students[0].course = & courses[0];
printf("Student 1: name=%s course=%s", students[0].name, students[0].course->title);
return;
}
Output:
Student 1: name=Charles course=C Language 101
Upvotes: 2