9

I have a GArray of GValue (all non-zero) which has been allocated at runtime with g_array_append_val. I wonder how can I find out what's the index of the last element, or more precisely how many elements does the array hold. Code like


for (length=0;g_value_get_int(&g_array_index(array, GValue, length)); length++);
return length

would fail with an out of bounds.

Reimundo Heluani
  • 918
  • 9
  • 18
  • 1
    It is up to you to keep track of the number of elements you have added to the garray. When created, a garray allocates a block of memory sufficient to hold a significant number of elements without reallocation and has a refcount of `1`. (this is done specifically to prevent frequent reallocation) I don't know of any way to tell exactly how many elements can be added before reallocation without looking at the glib source. See [**glib - Arrays**](https://developer.gnome.org/glib/stable/glib-Arrays.html) – David C. Rankin Nov 20 '15 at 21:26
  • 1
    @DavidC.Rankin Seems unlikely. How would `g_array_append_val` work if GArrays don't keep track of their size? – user253751 Nov 20 '15 at 22:10
  • Point well taken, that is why I referred the OP to the source, because it wasn't documented in the glib - Arrays documentation. – David C. Rankin Nov 20 '15 at 22:40

1 Answers1

19

It doesn't seem to be well-documented, but the number of the elements in the array is stored in the field array->len.

It's described here.

user253751
  • 57,427
  • 7
  • 48
  • 90
  • Thanks! Ohh man I should've looked at the source file at least! is right there in the first struct _GArray, the doxygen in the source file says /** * GArray: * data: a pointer to the element data. The data may be moved as * elements are added to the #GArray. * len: the number of elements in the #GArray not including the * possible terminating zero element. * * Contains the public fields of a GArray. */ – Reimundo Heluani Nov 20 '15 at 22:38
  • 2
    For future reference, it's documented [here](https://developer.gnome.org/glib/stable/glib-Arrays.html#GArray). – ptomato Nov 21 '15 at 00:31