[英]C quick sort of a struct causes segmentation fault
该程序正在从文件中逐行读取并将信息存储在结构中。 除对结构数组排序外,其他所有操作均有效。 例如,最后,当我打印struct(末尾包含的代码)时,它可以正常工作。
当我调用qsort时出现问题(分段错误)。
另外,打印students [0] .lastName可以正常工作,但是打印students [1] .lastName返回一个(空),这也很令人困惑。
我到处都看过了,我的代码似乎与作为正确的排序结构解决方案发布的代码非常相似,所以我很困惑。
在main标头中定义结构:
// DEFINE STRUCT
typedef struct _StudentInformation {
int term;
int studentId;
char *lastName;
char *firstName;
char *subject;
int catalogNumber;
char *section;
} StudentInformation;
在主要方法中分配结构(STUDENT_DATA = 50):
// ALLOCATE AN ARRAY OF STUDENTS (STRUCT)
StudentInformation *students;
if ((students = malloc(STUDENT_DATA*sizeof(StudentInformation)))==NULL) {
scanf("Error can't allocate enough students!\n");
exit(1);
}
问题:调用quicksort(之所以使用8,是因为有8个条目可以正常工作并被加载,甚至少于8个也不起作用):
qsort(students, 8, sizeof(StudentInformation), comparator);
快速排序比较器:
int comparator (const void * a, const void * b) {
StudentInformation *s1 = (StudentInformation*)a;
StudentInformation *s2 = (StudentInformation*)b;
return strcmp(s1->lastName, s2->lastName);
}
我知道数据可以很好地加载是因为打印完全正常:
void printInformation (StudentInformation *students) {
// PRINT EVERYTHING
while(students->firstName!=NULL) {
printf("%-s, %s %15d %4d %4s%d %7s\n",
students->lastName,students->firstName,students->term,
students->studentId, students->subject,students->catalogNumber,
students->section);
// Increment
students=students+sizeof(StudentInformation);
}
}
它打印的内容(我只打印了8个中的2个,不打印NULL):
Castille, Michael Jr 1201 103993269 CSE230 R03
Boatswain, Michael R. 1201 105515018 CSE230 R01
谢谢!
该行:
if ((students = malloc(STUDENT_DATA*sizeof(StudentInformation)))==NULL)
为结构本身分配内存,但不为指针引用的字符串分配内存:
char *lastName;
char *firstName;
char *subject;
char *section;
这些中的每一个都占用足够的内存来存储指针。 您需要分别为字符串分配内存:
if ((lastName = malloc((LAST_NAME_LEN + 1) * sizeof(char))) == NULL) {
// Error
}
if ((firstName = ...
编写不属于您的内存始终是调试ricochet-errors上意外课程的好方法:您最终可能会遇到segfault或内存损坏,但似乎在代码领域完全与问题的实际来源无关。
如果STUDENT_DATA> = 8,则只有一种可能的解释,那就是您的一个或多个lastName
字段从未被初始化,并且包含NULL或垃圾。 如果初始化这些字段的循环包含与打印循环相同的错误(使用students=students+sizeof(StudentInformation)
而不是students++
),这就是原因。
您说Calling quicksort (the reason for the 8 is because there are 8 entries
。
这是不正确的。 您应该传递数组中的元素数(在您的情况下为STUDENT_DATA
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.