G_list_nth_data -> (null)

Why does g_list_nth_data return (null) when I swap the records with g_list_reverse?

// gcc main.c -o main `pkg-config --cflags --libs glib-2.0 `

#include <glib.h>

int main(int argc, char** argv) {
  GList* list = 0;
  list = g_list_append(list, "Hello world 1 !");
  list = g_list_append(list, "Hello world 2 !");
  list = g_list_append(list, "Hello world 3 !");
  list = g_list_append(list, "Hello world 4 !");
  list = g_list_append(list, "Hello world 5 !");
  g_print("The first item is '%s'\n", g_list_first(list)->data);
  g_print("Der 2. Eintrag ist: %s\n", g_list_nth_data(list, 2)); // -> io.
  g_list_reverse(list);
  g_print("Der 2. Eintrag ist: %s\n", g_list_nth_data(list, 2)); // -> (null)
  return 0;
}

output:

$ ./main 
The first item is 'Hello world 1 !'
Der 2. Eintrag ist: Hello world 3 !
Der 2. Eintrag ist: (null)

Because you need to assign the return value, otherwise you’re just using the same pointer you passed, which now points to the end of the reversed list. See: GLib.List.reverse

So:

list = g_list_reverse (list);
1 Like