对指向结构体 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想这应该更简单..
而且我认为 qsort 函数调用绝对是正确的,如果它是这样的,
我认为第三个参数必须是结构的大小,你可以肯定地确定它是否是这样的就像上面的..
I guess this should be simpler..
And also I think the qsort function call could be definitely right if it were something like this,
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..