Search code examples
carraysglib

Replace value of given index using GArray of glib-library


Using GArray of the glib library I want to set the value at position x to a given value. Just like i do using c-array and array[x]=5;

Why can't I find any function to do so? Isn't this the meaning of an arrays? Documentation: https://developer.gnome.org/glib/stable/glib-Arrays.html

I could remove the old value and insert the new one. But this is kind of stupid. Is there a better way?

UPDATE:

On Gnome Bugzilla it was explaint to me this is the usual way:

int *element = &g_array_index (array, int, i);
*element = 42;

https://bugzilla.gnome.org/show_bug.cgi?id=764599


Solution

  • The documentation does not make this clear, but because g_array_index is a macro you can use it to set as well as get.

    g_array_index(foo, int, 0) = 23;
    g_array_index(foo, int, 1) = 42;
    

    Unfortunately it does not update nor check the size of the array kinda defeating the point of GArray. You'll either have to use g_array_sized_new or g_array_set_size to ensure there is enough allocated memory.

    I cannot find documentation nor an example of this. It should be documented beyond the vague mention in the description that you can use g_array_index to "access an element", but that's later contradicted by the g_array_index docs which says that it only "returns the element". Even better would be to provide g_array_set_val and have no confusion. Perhaps you can let them know?