gpt4 book ai didi

c - g_ptr_array_sort 不工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:54:42 25 4
gpt4 key购买 nike

我是 GPtrArray 的新手,遇到了一些问题。我像下面这样写了我的代码。但是g_ptr_arrat_sort(a, compare_items);不管用..我试图通过 gdb 进行调试,但我发现我的程序有问题..gdb 说, (gdb) p *阿尔法 $1 = {item = 6295648, name = 0x601080 "o\024", price = 6295712, value = 3.1105108254111529e-317} (gdb) p *测试版$3 = {item = 6295680, name = 0x6010a0 "/\"", price = 6295744, value = 0}

这不是我输入 GPtrArray* a 的内容!!

我该如何解决这个问题??

我的代码:

1 #include <stdio.h>
2 #include <glib.h>
3
4 typedef struct _DATA {
5 int item;
6 char* name;
7 int price;
8 double value;
9 } DATA;
10
11 int compare_items (gpointer, gpointer);
12 void printAll (gpointer, gpointer);
13
14 DATA data [] = {{7143, "aaa", 1231234, 235.5},
15 {5231, "bbb", 532458, 238.75},
16 {8751, "ccc", 872654, 125.47},
17 {2354, "ddd", 87542, 564.4}};
18
19 int main(void)
20 {
21 GPtrArray* a = g_ptr_array_new ();
22 g_ptr_array_add (a, &data[0]);
23 g_ptr_array_add (a, &data[1]);
24 g_ptr_array_add (a, &data[2]);
25 g_ptr_array_add (a, &data[3]);
26
27 g_ptr_array_sort (a, (GCompareFunc) compare_items);
28
29 g_ptr_array_foreach (a, printAll, (gpointer) NULL);
30
31 return 0;
32 }
33
34 gint compare_items (gpointer a, gpointer b) {
35
36 DATA* alpha = (DATA *) a;
37 DATA* beta = (DATA *) b;
38
39 return (gint) (alpha->item - beta->item);
40 }
41
42 void printAll (gpointer a, gpointer b) {
43 DATA* alpha = (DATA*) a;
44 printf ("item : %d, name : %s, price : %d, value : %lf\n", alpha -> item, alpha -> name, alpha -> price, alpha -> value);
45 return;
46 }

输出:

item : 7143, name : aaa, price : 1231234, value : 235.500000
item : 5231, name : bbb, price : 532458, value : 238.750000
item : 8751, name : ccc, price : 872654, value : 125.470000
item : 2354, name : ddd, price : 87542, value : 564.400000

最佳答案

根据 documentation ,

The comparison function for g_ptr_array_sort() doesn't take the pointers from the array as arguments, it takes pointers to the pointers in the array.

这意味着您的比较函数可能应该如下所示:

gint compare_items (gpointer a, gpointer b) {
DATA* alpha = *(DATA **) a;
DATA* beta = *(DATA **) b;
return (gint) (alpha->item - beta->item);
}

关于c - g_ptr_array_sort 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21970328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com