我想排序结构的指针数组,其中比较键是结构的属性之一。排序结构指针阵列qsort
我认为这可能是比较方法。
下面是一个示例代码。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct BINARY_ARRAY_RECORD {
char *name;
};
int compare(const void *node1, const void *node2) {
return strcmp(
((struct BINARY_ARRAY_RECORD *) node1)->name,
((struct BINARY_ARRAY_RECORD *) node2)->name
);
}
int main()
{
struct BINARY_ARRAY_RECORD **records;
records = malloc(sizeof(struct BINARY_ARRAY_RECORD *) * 2);
records[0] = malloc(sizeof(struct BINARY_ARRAY_RECORD));
records[1] = malloc(sizeof(struct BINARY_ARRAY_RECORD));
records[0]->name = malloc(sizeof(char) * (strlen("string2") + 1));
records[1]->name = malloc(sizeof(char) * (strlen("string1") + 1));
strcpy(records[0]->name, "string2");
strcpy(records[1]->name, "string1");
qsort(records, 2, sizeof(records[0]), compare);
printf("%s\n", records[0]->name);
printf("%s\n", records[1]->name);
return 0;
}
你的问题在哪里? – AlexTheo