Search code examples
carraysstringglib

g_array_sort not working on string


How using g_array_sort for strings in C? My code using compare string but I'cant get data

int porownanie(gpointer a, gpointer b)
 {
 char *str_a = (char *)a; char *str_b = (char *)b; 
  printf("[%s:%s]=%d\n",str_a,str_b,g_ascii_strcasecmp(str_a,str_b));  
 return strcmp(str_a,str_b);
 }

main function

GArray* t = g_array_new(FALSE, FALSE, sizeof(char*));
char* a = "a", *b = "c", *c = "d"....
g_array_append_val(t, a);....

prt(t);printf("Sortujemy\n"); g_array_sort(t, (GCompareFunc)porownanie);
prt(t); printf("Porownanie %d\n",porownanie((char *)"a",(char *)"b"));

I get :

Tablica: b a f c d  
[z_:t_]=6 
[v_:x_]=-2 
[|_:v_]=6 
[|_:x_]=4
[t_:v_]=-2 
[z_:v_]=4 
[z_:x_]=2 
[z_:|_]=-2 
Tablica: a c d b f 
[a:b]=-1 Porownanie -1

I'm not get char* from g_aray_sort, I get random data


Solution

  • The sort function receives a pointer to the item to be sorted, not the value itself. You need something like

    int porownanie(gpointer a, gpointer b)
    {
      char **str_a = (char **)a; char **str_b = (char **)b; 
      printf("[%s:%s]=%d\n",*str_a,*str_b,g_ascii_strcasecmp(*str_a,*str_b));  
      return strcmp(*str_a,*str_b);
    }
    

    FWIW, the rationale here is that the items could be anything, including large structs that you don't really want to copy around… think about what would happen if you had an array of

    struct Foo {
      guint8 input_buffer[4096];
      guint8 output_buffer[4096];
    }
    

    In fact, for strings you would generally use a GPtrArray, not a GArray. The sort function still requires char** arguments (because a GPtrArray is really just a convenience API around GArray), but it assumes values are sizeof(void*) and makes the API a bit easier to use.