[英]sort array of pointers to structures qsort
I'm trying to sort an array of pointers to structures where the key to compare is one of the structure's property. 我正在尝试对指向结构的指针进行排序,其中要比较的键是结构的属性之一。
I think that probably is the compare method. 我认为这可能是比较方法。
Here's an example code. 这是示例代码。
#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;
}
I guess this should be simpler.. 我想这应该更简单。
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);
}
And also I think the qsort function call could be definitely right if it were something like this, 而且我认为,如果是这样的话,qsort函数调用肯定是正确的,
qsort(records, 2, sizeof(BINARY_ARRAY_RECORD*), compare);
I think the third argument must be the size of the structure and you can be definitely be sure if it were something like the above.. 我认为第三个参数必须是结构的大小,您可以肯定地确定它是否类似于上面的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.