【发布时间】:2015-04-02 20:57:53
【问题描述】:
我目前有一个链表,需要向其中添加用户从键盘输入的数据,所以我有两个结构:
struct CourseInfo {
int courseID;
char courseName[30];
};
typedef struct CourseInfo courseinfo;
struct StudentInfo {
char StudentID[10];
char FirstName[21];
char LastName[26];
int num_course;
courseinfo array[10];
struct StudentInfo *next;
};
所以我目前有一个包含 3 个节点的链表。然后我需要调用一个函数并添加一个节点。节点需要插入到正确的位置,即之前的学生ID需要小于它,之后的学生ID需要更大,所以我拥有的当前ID是111111111、333333333和444444444,我正在尝试添加222222222所以它会放在第二个位置,所以我的函数看起来像:
studentinfo *addStudent(studentinfo *data) //returns type studentinfo* now
{
studentinfo *add;
add = malloc(sizeof(studentinfo));
add->next = NULL; //Now its set to NULL to begin
int knt;
printf("%s", "Adding new student:\nStudent ID: ");
scanf("%s", add->StudentID);
printf("%s", "First Name: ");
scanf("%s", add->FirstName);
printf("%s", "Last Name: ");
scanf("%s", add->LastName);
printf("%s", "Number of courses: ");
scanf("%d", &add->num_course);
for(knt = 0; knt < add->num_course; knt++) {
printf("%s", "Course ID: ");
scanf("%d", &add->array[knt].courseID);
printf("%s", "Course Name: ");
scanf("%s", add->array[knt].courseName);
}
if(searchStudentID(data, add->StudentID)) {
puts("immediately inside if");
while(data != NULL) {
puts("Immediately inside while");
if(strcmp(add->StudentID, data->StudentID) < 0) {
puts("inside if");
add->next = data;
data = add;
}
else {
puts("inside first else");
studentinfo *PrevPtr = data;
studentinfo *NPtr = data->next;
while(NPtr != NULL) {
("inside while(NPTR != NULL)");
if(strcmp(add->StudentID, NPtr->StudentID) < 0) {
add->next = PrevPtr;
PrevPtr->next = add;
break;
}
else {
puts("inside a differnet else");
PrevPtr = NPtr;
NPtr = NPtr->next;
}
}
if(PrevPtr->next == NULL) {
puts("inside last if");
add->next = NULL;
PrevPtr->next = add;
}
}
}
}
else {
puts("Found id");
}
return data; //returns data back to call
}
所以我添加了所有这些puts 语句,因为我想看看为什么程序不断崩溃。所以 puts 语句puts("Inside a different else") 陷入了无限循环并继续打印。如果我们还没有 ID,则函数 searchStudentID 仅返回 1,如果我们已经拥有它,则返回 0。我知道此功能有效,因此无需发布。
我认为问题可能出在休息区;语句,因为它不会从第一个 while 循环中退出,而只是从内部循环中退出,但我不是肯定的。对该函数的调用如下所示:
list = addStudent(list); //Now the new data is stored in list
list是3个节点的链表
【问题讨论】:
-
您是否使用调试器浏览过代码
-
@pm100 我目前正在使用 code::blocks,当我构建和运行时我没有收到任何错误
-
不相关,else 子句中的最后一条消息应为:“Found id and leaked memory” 关于实际问题,只要在您执行此操作的任何地方说明就足够了:
data = (anything)表示 nothing 回到此函数的调用方。 -
调试器是一种工具,可让您探索程序的执行情况。即逐行浏览它,看看它在做什么。你应该学会使用一个
标签: c linked-list nodes