[英]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.