GNOME Bugzilla – Bug 764599
Missing documentation how to set a value in a GArray
Last modified: 2018-05-24 18:49:11 UTC
It is quite hard to find a way to set a value on a given index in a GArray (like you do with array[0]=4 using c-array). Thanks to Stackoverflow user Schwern (http://stackoverflow.com/questions/36403775/replace-value-of-given-index-using-garray-of-glib-library) I now know, you can use g_array_index, but it is nowhere documented nor can I find an example. It would be helpful to add this to documentation or even add a g_array_set_val function/macro.
The usual way to replace a value is to obtain a pointer to it, and then replace the contents at the pointed location, e.g.: int *element = &g_array_index (array, int, i); *element = 42; Though, obviously, using GArray for integers is a bit lame; if you use a structure it becomes slightly more obvious: Person *p = &g_array_index (array, Person, i); p->name = g_strdup ("Emmanuele"); p->surname = g_strdup ("Bassi"); which is an idiomatic use that is, indeed, described in the API reference for GArray: https://developer.gnome.org/glib/stable/glib-Arrays.html#g-array-index ``` EDayViewEvent *event; // This gets a pointer to the 4th element in the array of // EDayViewEvent structs. event = &g_array_index (events, EDayViewEvent, 3); ``` We can definitely improve the documentation with more examples, though. > It would be helpful to add this to documentation or even add a > g_array_set_val function/macro. I'm not entirely sure what `g_array_set_val()` would do, except provide the same syntactic sugar as `g_array_index()`.
-- 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/1154.