GNOME Bugzilla – Bug 113697
g_ptr_array_sort_[with_data] is twisted
Last modified: 2018-05-23 23:15:11 UTC
What's wrong with the following code? g_ptr_array_sort (ptr_array, (GCompareFunc)strcmp); Answer: The comparison function for g_ptr_array_sort_[with_data] doesn't take the the pointers from the array, it takes pointers to the pointers in the array. This was, I suspect, an accidental oversight, but I doubt we can change it at this point. Two possible steps moving forward: - Add warning notes to the docs with big exclamation points (Should definitely do this) - Add another set of functions that behave as expected and deprecate the current ones. I don't know what you would call the new functions.
I've added a note to the docs now.
perhaps adding a short sample to the docs would help. It would have saved me a lot of mucking around. enum { SORT_NAME, SORT_SIZE }; typedef struct filelist_entry { gchar *name; gint size; } filelistEntry; gint sort_filelist(gconstpointer a, gconstpointer b, gint *sort_mode) { gint order; filelistEntry *flent1 = *((filelistEntry**)a); filelistEntry *flent2 = *((filelistEntry**)b); switch(*sort_mode) { case SORT_NAME: order = g_ascii_strcasecmp(flent1->name, flent2->name); break; case SORT_SIZE: if (flent1->size = flent2->size) order = 0; else if (flent1->size < flent2->size) order = -1; else order = 1; break; } return order; } GPtrArray *filelist; gint sort_mode; /* initialize filelist array and load with many a filelistEntry */ ... /* now sort it with */ sort_mode = SORT_NAME; g_ptr_array_sort_with_data(filelist, (GCompareDataFunc)sort_filelist, &sort_mode); Lee Bigelow ligelowbee@yahoo.com
(umm, sorry about that... I was using w3m and emacs as my editor. It's usually quite a wicked combo, huh. firefox it is then.) perhaps adding a short sample to the docs would help. It would have saved me a lot of mucking around. enum { SORT_NAME, SORT_SIZE }; typedef struct filelist_entry { gchar *name; gint size; } filelistEntry; gint sort_filelist(gconstpointer a, gconstpointer b, gint *sort_mode) { gint order; filelistEntry *flent1 = *((filelistEntry**)a); filelistEntry *flent2 = *((filelistEntry**)b); switch(*sort_mode) { case SORT_NAME: order = g_ascii_strcasecmp(flent1->name, flent2->name); break; case SORT_SIZE: if (flent1->size = flent2->size) order = 0; else if (flent1->size < flent2->size) order = -1; else order = 1; break; default: order = 0; break; } return order; } GPtrArray *filelist; gint sort_mode; /* initialize filelist array and load with many a filelistEntry */ ... /* now sort it with */ sort_mode = SORT_NAME; g_ptr_array_sort_with_data(filelist, (GCompareDataFunc)sort_filelist, &sort_mode);
-- GitLab Migration Automatic Message -- This bug has been migrated to GNOME's GitLab instance and has been closed from further activity. You can subscribe and participate further through the new bug through this link to our GitLab instance: https://gitlab.gnome.org/GNOME/glib/issues/9.