C语言 使用qsort对结构体数组进行排序



我是C的新手,如果有明显的错误,我深表歉意。我想用qsort按字母顺序排序这个列表。我想出了这个,但是由于某种原因,我的排序函数没有返回任何东西。没有错误,只是空白。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// struct person with 3 fields
struct People {
char* name;
char age;
};
static int myCompare(const void* a, const void* b)
{

// setting up rules for comparison
return strcmp(*(const char**)a, *(const char**)b);
}
// Function to sort the array
void sort(const char* arr[], int n)
{
// calling qsort function to sort the array
qsort(arr, n, sizeof(const char*), myCompare);
}
int main()
{
int i = 0, n = 17;
struct People arr[n];
// Make people list
arr[0].name = "Bell";
arr[0].age = 20;
arr[1].name = "Tan";
arr[1].age = 31;
arr[2].name = "Jones";
arr[2].age = 19;
// Sort the given names
sort(arr, n);
// Print the sorted names
printf("nSorted array isn");
for (i = 0; i < n; i++)
printf("%d: %s n", i, arr[i]);

return 0;
}

有很多问题。我有一个强烈的印象,你试图盲目地修改一些代码,这些代码应该在不了解基础知识的情况下将指针排序到char*

你想要这个,在注释中解释:

static int myCompare(const void* a, const void* b)
{
return strcmp(((struct People *)a)->name, ((struct People*)b)->name);
}
void sort(struct People arr[], int n)              // you want to sort an array
// of struct People
{
// calling qsort function to sort the array
qsort(arr, n, sizeof(struct People), myCompare); // the size of your elements is
// sizeof(struct People), 
// not size of (char*)
}
int main()
{
int i = 0, n = 3;          // you don't have 17 elements, you only have 3
// With the original value 17 you would sort
// 17 elements, but your array contains
// only 3 elements, the other 14 ones
// are uninitialized
struct People arr[n];
// Make people list
arr[0].name = "Bell";
arr[0].age = 20;
arr[1].name = "Tan";
arr[1].age = 31;
arr[2].name = "Jones";
arr[2].age = 19;
// Sort the given names
sort(arr, n);
// Print the sorted names
printf("nSorted array isn");
for (i = 0; i < n; i++)
printf("%d: %s n", i, arr[i].name);   // you want to print the name,
// not a struct People
return 0;
}

myCompare((struct People *)a)->name的解释

比较函数有3个形参,第一个和第二个是要比较的元素的指针,第三个是元素的大小。

(struct People *)a)将void指针a转换为指向struct People的指针。->操作符访问name字段。

如果要按年龄排序,只需替换

strcmp(((struct People *)a)->name, ((struct People*)b)->name)

((struct People *)a)->age < ((struct People*)b)->age

最新更新