Search code examples
arrayscglib

How do I get an element by index from a GLib GArray?


I'm writing an application which depends on GLib, so I am using its dynamic arrays as well. Reading the docs for GLib.Array, it looks like I should be able to access the array's data via the data property of the structure. However, in practice, it doesn't seem like I'm able to read this data the usual way via bracket notation:

struct TestStruct {
    bool some_value;
    int some_other_value;
};

int main(int argc, char *argv[]) {
    GArray* test_array = g_array_new(false, false, sizeof(struct TestStruct));
    struct TestStruct test_struct = { .some_value = true, .some_other_value = 4 };
    g_array_append_val(test_array, test_struct);
    struct TestStruct test_struct_2 = { .some_value = false, .some_other_value = 9 };
    g_array_append_val(test_array, test_struct_2);

    printf("%i\n", test_array->data[0].some_other_value);
}

If I try to compile this, I get the following error:

../../../../../../../../../Projects/test/src/main.c:214:45: error: invalid type argument of ‘->’ (have ‘int’)
  214 |         printf("%i\n", (test_array->data)[0]->some_other_value);
      |                                             ^~

I've also tried dot notation instead of the arrow to access the property, but it doesn't help since test_array->data[0] is an int in this context, which obviously can't have access operations made on it like that.

With that in mind, how do I actually get an element from a GArray by index?


Solution

  • How do I actually get an element from a GArray by index?

    using the g_array_index macro with args (array, element type, index)

    as in

    g_array_index(test_array, struct TestStruct, 0).some_other_value