[英]sort array of pointers to structures 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;
}
我想这应该更简单。
int compare(const void *node1, const void *node2) {
BINARY_ARRAY_RECORD *ptr1 = *(BINARY_ARRAY_RECORD * const *)node1;
BINARY_ARRAY_RECORD *ptr2 = *(BINARY_ARRAY_RECORD * const *)node2;
return strcmp(ptr1->name, ptr2->name);
}
而且我认为,如果是这样的话,qsort函数调用肯定是正确的,
qsort(records, 2, sizeof(BINARY_ARRAY_RECORD*), compare);
我认为第三个参数必须是结构的大小,您可以肯定地确定它是否类似于上面的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.