Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用qsort对结构排序(按“姓氏”字段排序)_C_Sorting_Structure_Qsort - Fatal编程技术网

C 使用qsort对结构排序(按“姓氏”字段排序)

C 使用qsort对结构排序(按“姓氏”字段排序),c,sorting,structure,qsort,C,Sorting,Structure,Qsort,我有这个部分,首先我将使用它创建员工结构: typedef struct { char first_name[20], last_name[20]; int birthdate, temporary; //date of birth YEAR/MONTH/DAY //temporary employees: 1, else 0 }factory; 我将使用以下功能读取数据: void readin

我有这个部分,首先我将使用它创建员工结构:

    typedef struct 
    { 
       char first_name[20], last_name[20]; 
       int birthdate, temporary; 
       //date of birth YEAR/MONTH/DAY
       //temporary employees: 1, else 0

    }factory;
我将使用以下功能读取数据:

    void reading(factory *employee,int *nr) 
    { 
      ++(*nr); 
      printf("First name:\n");
      fflush(stdin); 
      gets((employee+*nr)->first_name);

      printf("Last name:\n");
      fflush(stdin); 
      gets((employee+*nr)->last_name);

      printf("Birthdate:\n");
      fflush(stdin);
      scanf ("%d" , &((employee + *nr)->birthdate));

      printf("Temporary employee? 1 for YES, 0 for NO");
      fflush(stdin);
      scanf("%d", &((employee + *nr)->temporary));

    }
还有比较函数,我认为它写得不好,任何关于如何修改它的建议都会很好-应该是factory employee*ia而不是struct吗

int struct_cmp_by_name(const void *a, const void *b)
{
struct employee *ia = (struct employee *)a;
struct employee *ib = (struct employee *)b;
return strcmp(ia->last_name, ib->last_name);

}
我还有一个简单的显示功能,我将在下面复制它的原型:

void display(factory *employee, int nr) 
为了节省空间,代码的其他部分被省略了。在这种情况下,我将如何实现qsort函数?我有比较函数,但我不知道基数组应该是什么,也不知道如何找到其他两个大小参数。感谢您提供的任何帮助

应该是

工厂*ia=工厂*a

或者你可以跳过作业,直接投

。。。工厂*a->姓氏

我假设您在代码的某个地方为工厂数组分配或声明了空间

对于快速排序,您可以交换结构,也可以创建指向结构和交换指针的指针数组。

请注意:调用fflushstdin是未定义的行为。你可能想找到另一种方法。另外,扔掉get,改用fgets。qsort的实际调用在哪里?这对于解决您的问题似乎有些重要。假设您的排序床是一个有效的工厂数组,那么您的比较器看起来是正确的,因为这些指针明显错误地缺少常量。请使用标准库qsort,+*nr;:*nr是start-1吗?