c - C中的结构内部结构(链表)
问题描述
我正在尝试编写一个程序,该程序允许我按顺序打印教师的信息,包括学生 ID。例如:当我尝试运行程序时,输出将类似于以下内容:
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);
}
为了组合这些列表,您可能需要编写一些函数来创建教师并将其添加到列表中,并将学生添加到教师中。然后首先调用这些函数来组装列表。
推荐阅读
- c++ - 如何在函数/方法中使用 sf::window
- sql - 如何对具有匹配 ID 的字段值求和?
- css - 应该如何格式化我的 scss 类名来达到这个效果?
- javascript - c++函数的执行与js函数有什么不同?
- python - 我的子类无法从 Python 中的父类正确继承
- vue.js - 如何使用 $nextTick 在 vue.js 中渲染 Plotly 图表
- bash - 如何使用 sed 在最后一次出现的字符串的最后一个字符之前添加一个单词?
- android - 来自图像颤动火力基础的文本识别
- javascript - model.find 方法未从数据库返回必填字段
- python - 如何在单元测试中模拟 ParameterNotFound boto3 异常?