Arrays

Arrays — arrays of arbitrary elements which grow automatically as elements are added

Functions

Types and Values

struct GArray

Includes

#include <gmodule.h>

Description

Arrays are similar to standard C arrays, except that they grow automatically as elements are added.

Array elements can be of any size (though all elements of one array are the same size), and the array can be automatically cleared to '0's and zero-terminated.

To create a new array use g_array_new().

To add elements to an array with a cost of O(n) at worst, use g_array_append_val(), g_array_append_vals(), g_array_prepend_val(), g_array_prepend_vals(), g_array_insert_val() and g_array_insert_vals().

To access an element of an array in O(1) (to read it or to write it), use g_array_index().

To set the size of an array, use g_array_set_size().

To free an array, use g_array_unref() or g_array_free().

All the sort functions are internally calling a quick-sort (or similar) function with an average cost of O(n log(n)) and a worst case cost of O(n^2).

Here is an example that stores integers in a GArray:

1
2
3
4
5
6
7
8
9
10
11
12
GArray *garray;
gint i;
// We create a new array to store gint values.
// We don't want it zero-terminated or cleared to 0's.
garray = g_array_new (FALSE, FALSE, sizeof (gint));
for (i = 0; i < 10000; i++)
  g_array_append_val (garray, i);
for (i = 0; i < 10000; i++)
  if (g_array_index (garray, gint, i) != i)
    g_print ("ERROR: got %d instead of %d\n",
             g_array_index (garray, gint, i), i);
g_array_free (garray, TRUE);

Functions

g_array_new ()

GArray *
g_array_new (gboolean zero_terminated,
             gboolean clear_,
             guint element_size);

Creates a new GArray with a reference count of 1.

Parameters

zero_terminated

TRUE if the array should have an extra element at the end which is set to 0

 

clear_

TRUE if GArray elements should be automatically cleared to 0 when they are allocated

 

element_size

the size of each element in bytes

 

Returns

the new GArray


g_array_steal ()

gpointer
g_array_steal (GArray *array,
               gsize *len);

Frees the data in the array and resets the size to zero, while the underlying array is preserved for use elsewhere and returned to the caller.

If the array was created with the zero_terminate property set to TRUE, the returned data is zero terminated too.

If array elements contain dynamically-allocated memory, the array elements should also be freed by the caller.

A short example of use:

1
2
3
4
5
...
gpointer data;
gsize data_len;
data = g_array_steal (some_array, &data_len);
...

Parameters

array

a GArray.

 

len

pointer to retrieve the number of elements of the original array.

[optional][out]

Returns

the element data, which should be freed using g_free().

[transfer full]

Since: 2.64


g_array_sized_new ()

GArray *
g_array_sized_new (gboolean zero_terminated,
                   gboolean clear_,
                   guint element_size,
                   guint reserved_size);

Creates a new GArray with reserved_size elements preallocated and a reference count of 1. This avoids frequent reallocation, if you are going to add many elements to the array. Note however that the size of the array is still 0.

Parameters

zero_terminated

TRUE if the array should have an extra element at the end with all bits cleared

 

clear_

TRUE if all bits in the array should be cleared to 0 on allocation

 

element_size

size of each element in the array

 

reserved_size

number of elements preallocated

 

Returns

the new GArray


g_array_copy ()

GArray *
g_array_copy (GArray *array);

Create a shallow copy of a GArray. If the array elements consist of pointers to data, the pointers are copied but the actual data is not.

Parameters

array

A GArray.

 

Returns

A copy of array .

[transfer container]

Since: 2.62


g_array_ref ()

GArray *
g_array_ref (GArray *array);

Atomically increments the reference count of array by one. This function is thread-safe and may be called from any thread.

Parameters

array

A GArray

 

Returns

The passed in GArray

Since: 2.22


g_array_unref ()

void
g_array_unref (GArray *array);

Atomically decrements the reference count of array by one. If the reference count drops to 0, all memory allocated by the array is released. This function is thread-safe and may be called from any thread.

Parameters

array

A GArray

 

Since: 2.22


g_array_get_element_size ()

guint
g_array_get_element_size (GArray *array);

Gets the size of the elements in array .

Parameters

array

A GArray

 

Returns

Size of each element, in bytes

Since: 2.22


g_array_append_val()

#define             g_array_append_val(a,v)

Adds the value on to the end of the array. The array will grow in size automatically if necessary.

g_array_append_val() is a macro which uses a reference to the value parameter v . This means that you cannot use it with literal values such as "27". You must use variables.

Parameters

a

a GArray

 

v

the value to append to the GArray

 

Returns

the GArray


g_array_append_vals ()

GArray *
g_array_append_vals (GArray *array,
                     gconstpointer data,
                     guint len);

Adds len elements onto the end of the array.

Parameters

array

a GArray

 

data

a pointer to the elements to append to the end of the array.

[not nullable]

len

the number of elements to append

 

Returns

the GArray


g_array_prepend_val()

#define             g_array_prepend_val(a,v)

Adds the value on to the start of the array. The array will grow in size automatically if necessary.

This operation is slower than g_array_append_val() since the existing elements in the array have to be moved to make space for the new element.

g_array_prepend_val() is a macro which uses a reference to the value parameter v . This means that you cannot use it with literal values such as "27". You must use variables.

Parameters

a

a GArray

 

v

the value to prepend to the GArray

 

Returns

the GArray


g_array_prepend_vals ()

GArray *
g_array_prepend_vals (GArray *array,
                      gconstpointer data,
                      guint len);

Adds len elements onto the start of the array.

data may be NULL if (and only if) len is zero. If len is zero, this function is a no-op.

This operation is slower than g_array_append_vals() since the existing elements in the array have to be moved to make space for the new elements.

Parameters

array

a GArray

 

data

a pointer to the elements to prepend to the start of the array.

[nullable]

len

the number of elements to prepend, which may be zero

 

Returns

the GArray


g_array_insert_val()

#define             g_array_insert_val(a,i,v)

Inserts an element into an array at the given index.

g_array_insert_val() is a macro which uses a reference to the value parameter v . This means that you cannot use it with literal values such as "27". You must use variables.

Parameters

a

a GArray

 

i

the index to place the element at

 

v

the value to insert into the array

 

Returns

the GArray


g_array_insert_vals ()

GArray *
g_array_insert_vals (GArray *array,
                     guint index_,
                     gconstpointer data,
                     guint len);

Inserts len elements into a GArray at the given index.

If index_ is greater than the array’s current length, the array is expanded. The elements between the old end of the array and the newly inserted elements will be initialised to zero if the array was configured to clear elements; otherwise their values will be undefined.

If index_ is less than the array’s current length, new entries will be inserted into the array, and the existing entries above index_ will be moved upwards.

data may be NULL if (and only if) len is zero. If len is zero, this function is a no-op.

Parameters

array

a GArray

 

index_

the index to place the elements at

 

data

a pointer to the elements to insert.

[nullable]

len

the number of elements to insert

 

Returns

the GArray


g_array_remove_index ()

GArray *
g_array_remove_index (GArray *array,
                      guint index_);

Removes the element at the given index from a GArray. The following elements are moved down one place.

Parameters

array

a GArray

 

index_

the index of the element to remove

 

Returns

the GArray


g_array_remove_index_fast ()

GArray *
g_array_remove_index_fast (GArray *array,
                           guint index_);

Removes the element at the given index from a GArray. The last element in the array is used to fill in the space, so this function does not preserve the order of the GArray. But it is faster than g_array_remove_index().

Parameters

array

a GArray

 

index_

the index of the element to remove

 

Returns

the GArray


g_array_remove_range ()

GArray *
g_array_remove_range (GArray *array,
                      guint index_,
                      guint length);

Removes the given number of elements starting at the given index from a GArray. The following elements are moved to close the gap.

Parameters

array

a GArray

 

index_

the index of the first element to remove

 

length

the number of elements to remove

 

Returns

the GArray

Since: 2.4


g_array_sort ()

void
g_array_sort (GArray *array,
              GCompareFunc compare_func);

Sorts a GArray using compare_func which should be a qsort()-style comparison function (returns less than zero for first arg is less than second arg, zero for equal, greater zero if first arg is greater than second arg).

This is guaranteed to be a stable sort since version 2.32.

Parameters

array

a GArray

 

compare_func

comparison function

 

g_array_sort_with_data ()

void
g_array_sort_with_data (GArray *array,
                        GCompareDataFunc compare_func,
                        gpointer user_data);

Like g_array_sort(), but the comparison function receives an extra user data argument.

This is guaranteed to be a stable sort since version 2.32.

There used to be a comment here about making the sort stable by using the addresses of the elements in the comparison function. This did not actually work, so any such code should be removed.

Parameters

array

a GArray

 

compare_func

comparison function

 

user_data

data to pass to compare_func

 

g_array_binary_search ()

gboolean
g_array_binary_search (GArray *array,
                       gconstpointer target,
                       GCompareFunc compare_func,
                       guint *out_match_index);

Checks whether target exists in array by performing a binary search based on the given comparison function compare_func which get pointers to items as arguments. If the element is found, TRUE is returned and the element’s index is returned in out_match_index (if non-NULL). Otherwise, FALSE is returned and out_match_index is undefined. If target exists multiple times in array , the index of the first instance is returned. This search is using a binary search, so the array must absolutely be sorted to return a correct result (if not, the function may produce false-negative).

This example defines a comparison function and search an element in a GArray:

1
2
3
4
5
6
7
8
9
10
11
12
13
static gint*
cmpint (gconstpointer a, gconstpointer b)
{
  const gint *_a = a;
  const gint *_b = b;

  return *_a - *_b;
}
...
gint i = 424242;
guint matched_index;
gboolean result = g_array_binary_search (garray, &i, cmpint, &matched_index);
...

Parameters

array

a GArray.

 

target

a pointer to the item to look up.

 

compare_func

A GCompareFunc used to locate target .

 

out_match_index

return location for the index of the element, if found.

[optional][out]

Returns

TRUE if target is one of the elements of array , FALSE otherwise.

Since: 2.62


g_array_index()

#define             g_array_index(a,t,i)

Returns the element of a GArray at the given index. The return value is cast to the given type. This is the main way to read or write an element in a GArray.

Writing an element is typically done by reference, as in the following example. This example gets a pointer to an element in a GArray, and then writes to a field in it:

1
2
3
4
5
EDayViewEvent *event;
// This gets a pointer to the 4th element in the array of
// EDayViewEvent structs.
event = &g_array_index (events, EDayViewEvent, 3);
event->start_time = g_get_current_time ();

This example reads from and writes to an array of integers:

1
2
3
4
5
6
7
g_autoptr(GArray) int_array = g_array_new (FALSE, FALSE, sizeof (guint));
for (guint i = 0; i < 10; i++)
  g_array_append_val (int_array, i);

guint *my_int = &g_array_index (int_array, guint, 1);
g_print ("Int at index 1 is %u; decrementing it\n", *my_int);
*my_int = *my_int - 1;

Parameters

a

a GArray

 

t

the type of the elements

 

i

the index of the element to return

 

Returns

the element of the GArray at the index given by i


g_array_set_size ()

GArray *
g_array_set_size (GArray *array,
                  guint length);

Sets the size of the array, expanding it if necessary. If the array was created with clear_ set to TRUE, the new elements are set to 0.

Parameters

array

a GArray

 

length

the new size of the GArray

 

Returns

the GArray


g_array_set_clear_func ()

void
g_array_set_clear_func (GArray *array,
                        GDestroyNotify clear_func);

Sets a function to clear an element of array .

The clear_func will be called when an element in the array data segment is removed and when the array is freed and data segment is deallocated as well. clear_func will be passed a pointer to the element to clear, rather than the element itself.

Note that in contrast with other uses of GDestroyNotify functions, clear_func is expected to clear the contents of the array element it is given, but not free the element itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
typedef struct
{
  gchar *str;
  GObject *obj;
} ArrayElement;

static void
array_element_clear (ArrayElement *element)
{
  g_clear_pointer (&element->str, g_free);
  g_clear_object (&element->obj);
}

// main code
GArray *garray = g_array_new (FALSE, FALSE, sizeof (ArrayElement));
g_array_set_clear_func (garray, (GDestroyNotify) array_element_clear);
// assign data to the structure
g_array_free (garray, TRUE);

Parameters

array

A GArray

 

clear_func

a function to clear an element of array

 

Since: 2.32


g_array_free ()

gchar *
g_array_free (GArray *array,
              gboolean free_segment);

Frees the memory allocated for the GArray. If free_segment is TRUE it frees the memory block holding the elements as well. Pass FALSE if you want to free the GArray wrapper but preserve the underlying array for use elsewhere. If the reference count of array is greater than one, the GArray wrapper is preserved but the size of array will be set to zero.

If array contents point to dynamically-allocated memory, they should be freed separately if free_seg is TRUE and no clear_func function has been set for array .

This function is not thread-safe. If using a GArray from multiple threads, use only the atomic g_array_ref() and g_array_unref() functions.

Parameters

array

a GArray

 

free_segment

if TRUE the actual element data is freed as well

 

Returns

the element data if free_segment is FALSE, otherwise NULL. The element data should be freed using g_free().

Types and Values

struct GArray

struct GArray {
  gchar *data;
  guint len;
};

Contains the public fields of a GArray.

Members

gchar *data;

a pointer to the element data. The data may be moved as elements are added to the GArray.

 

guint len;

the number of elements in the GArray not including the possible terminating zero element.