c - 如何使用来自用户的输入创建表,其数量根据用户先前指定的输入而变化?
问题描述
我不允许使用数组。我需要列出用户在第一次 scanf_s 调用中指定的所有课程代码、日期和时间。我不知道如何在不使用数组的情况下进行。任何帮助提示/帮助将不胜感激。
printf("Please enter the number of courses you'd like to take: ");
int numOfCourses;
scanf_s("%d", &numOfCourses);
int courseCode;
int courseDay;
int courseTime;
int i = 0;
while (i < numOfCourses) {
printf("Please enter the code of the course: ");
scanf_s("%d", &courseCode);
printf("Please enter the day of the course: ");
scanf_s("%d", &courseDay);
printf("Please enter the time of the course: ");
scanf_s("%d", &courseTime);
i++;
}
解决方案
在链表中使用动态内存分配。看malloc
。您的列表结构可能如下所示:
typedef struct COURSES {
int courseCode;
int courseDay;
int courseTime;
struct COURSES *next;
} t_Courses;
您按如下方式分配列表元素:
t_Courses *pCourse= malloc(sizeof(t_Courses));
然后像现在一样读取数据,例如:
scanf_s("%d", &pCourse->courseCode);
管理一个链表并不简单。我把它留给你作为家庭作业的一部分。互联网和 Stack Exchange 上有很多示例。