[英]Structure inside structure in C (Linked List)
我正在尝试编写一个程序,该程序允许我按顺序打印教师的信息,包括学生 ID。 例如:当我尝试运行程序时,output 将类似于以下内容:
Teacher Apple, Age 55:
Student ID: 77
Student ID: 5456
Student ID: 4729
Student ID: 3784
Teacher bob, Age 67:
Student ID: 477
Student ID: 546
Student ID: 429
Student ID: 784
.. 等等。
但是,我想不出一种以正确格式打印它们的方法。 我在使用嵌套循环时遇到问题。 这是我的代码:
struct Teacher {
char* name;
int age;
struct Student* stds;
struct Teacher* next;
};
struct Student
{
int id;
struct Student* next;
};
int main() {
//aray to store teachers' names
char names[3][10] = { "first", "second", "third" };
//their age
int age[3] = { 1,2,3 };
//students' id
int id[4] = { 1, 2, 3, 4 };
//alocate the linkedlist in mem
struct Teacher* head = (struct Teacher*)malloc(sizeof(struct Teacher));
struct Student* headstd = (struct Student*)malloc(sizeof(struct Student));
head->next = NULL;
headstd->next = NULL;
//head ->next = (struct Teacher*)malloc(sizeof(struct Teacher));
//adding temporary head and modefied it so I don't touch the actual head
struct Teacher* temhead = (struct Teacher*)malloc(sizeof(struct Teacher));
struct Student* stdhead = (struct Student*)malloc(sizeof(struct Student));
//head->name =
//(char)first.name ="first";
temhead->next = NULL;
stdhead->next = NULL;
///loop thorough the teachers
for (int i = 0; i < 3; i++) {
//loop through the students
for (int j = 0; j < 4; j++) {
stdhead->next = (struct Student*)malloc(sizeof(struct Student));
stdhead = stdhead->next;
stdhead->id = *(id + j);
//temhead->age = 44;
printf("Student ID: %d \n ", stdhead->id);
}
//here after it goes through the students, it goes through teachers
temhead->next = (struct Teacher*)malloc(sizeof(struct Teacher));
temhead = temhead->next;
//here I assigned the name of teachers to the array I have implementd @ first (names[3][10]
temhead->name = *(names + i);
//print names (for now "first, second, ..")
printf("node: %s \n ", temhead->name);
}
//
// for (int i = 0; i < 3; i++) {
// temhead->next = (struct Teacher*)malloc(sizeof(struct Teacher));
// //temhead->stds = (struct Teacher*)malloc(sizeof(struct Teacher));
// temhead = temhead->next;
// temhead->age = *(age + i);
// //temhead->age = 44;
// printf("%d \n ", temhead->age);
//
// }
//
//
//}
打印代码可能看起来像这样。 但是,除非您首先正确地组装教师和学生,否则它不会起作用。
for (struct Teacher *t = head; t != NULL; t = t->next)
{
printf("Teacher %s, Age %d:\n", t->name, t->age);
for (struct Student *s = t->stds; s != NULL; s = s->next)
printf("Student ID: %d\n", s->id);
}
为了组合这些列表,您可能需要编写一些函数来创建教师并将其添加到列表中,并将学生添加到教师中。 然后首先调用这些函数来组装列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.