C快速排序结构导致分段错误

ano*_*non 2 c struct memory-management qsort

程序从文件中逐行读取并在结构中存储信息.一切都有效,除了排序结构数组.例如,在我打印结构(最后包含的代码)的最后,它完全正常.

当我调用qsort时会出现问题(分段错误).

此外,打印学生[0] .lastName工作正常,但打印学生[1] .lastName返回一个(null),这也是令人困惑的.

我到处寻找,我的代码看起来非常类似于已经发布的排序结构的正确解决方案,所以我很困惑.

在main的头文件中定义struct:

// DEFINE STRUCT
typedef struct _StudentInformation  {
    int term;
    int studentId;
    char *lastName;
    char *firstName;
    char *subject;
    int catalogNumber;
    char *section;
} StudentInformation;
Run Code Online (Sandbox Code Playgroud)

在main方法中分配struct(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);
}
Run Code Online (Sandbox Code Playgroud)

问题:调用quicksort(8的原因是因为有8个条目工作并且被加载,甚至少于8个不起作用):

qsort(students, 8, sizeof(StudentInformation), comparator);
Run Code Online (Sandbox Code Playgroud)

快速排序比较器:

int comparator (const void * a, const void * b) {
    StudentInformation *s1 = (StudentInformation*)a;
    StudentInformation *s2 = (StudentInformation*)b;

    return strcmp(s1->lastName, s2->lastName);
}
Run Code Online (Sandbox Code Playgroud)

我知道数据加载正常的原因是因为打印工作完全正常:

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);
        }
}
Run Code Online (Sandbox Code Playgroud)

它打印的内容(我只包括打印的8个中的2个,没有打印NULLS):

Castille, Michael Jr            1201 103993269  CSE230     R03
Boatswain, Michael R.            1201 105515018  CSE230     R01
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ada*_*iss 5

这条线:

if ((students = malloc(STUDENT_DATA*sizeof(StudentInformation)))==NULL)
Run Code Online (Sandbox Code Playgroud)

为结构本身分配内存,但不为指针引用的字符串分配内存:

char *lastName;
char *firstName;
char *subject;
char *section;
Run Code Online (Sandbox Code Playgroud)

其中每个占用指针的足够内存.您需要分别为字符串分配内存:

if ((lastName = malloc((LAST_NAME_LEN + 1) * sizeof(char))) == NULL) {
  // Error
}
if ((firstName = ...
Run Code Online (Sandbox Code Playgroud)

写入你不拥有的内存总是一个很好的方法来获得调试跳转错误的意外课程:你最终可能会遇到段错误或内存损坏,但它可能在代码区域似乎是与问题的实际根源完全无关.