Skip to content
Srđan Panić edited this page Mar 14, 2016 · 3 revisions

Array

Creating arrays

Creating an array with default settings:

Array *a = array_new();

Most of the time this is sufficient, but sometimes we may want to have more control over how the structure is created and how it will behave. For example if we wanted to specify the initial capacity and the growth rate we would use the ArrayConf struct to configure the array on creation.

ArrayConf ac;

// We can initialize the array config struct if we don't want to set each value ourselves.
// This is useful if we're not intereseted in all of the options.
array_conf_init(&ac);

// The inital capacity
ac.capacity = 10;

// The expansion factor or growth rate. In this case we set it to 0.5 or 50% which means
// that the array will grow by 50% on each internal resize.
ac.exp_factor = 0.5f;

// Now we can create a new array with 
Array *ar = array_new_conf(&ac);

Destroying arrays

We can free the Array structure by calling array_destroy

array_destroy(array);

If we also wanted to free all the elements it holds along with the structure we could use array_destroy_free.

// All the elements are freed along with the structure
array_destroy_free(array);

Adding elements

Array *ar = array_new();

// Add an element to the array, or more specifically append it to the end of the array.
array_add(ar, "foo");

// This function accepts void*, we can pass any pointer to it, however having multiple types
// of things in a single structure may not be a good idea.
int e = 42;
array_add(ar, &e);

// It is generally not possible to pass the value directly, but if the value we want to pass
// can fit inside a void* we could do something like this:
array_add(ar, (void*) 42); 

// We could also add an element at a specific index:
array_add_at(ar, "bar", 1);

// or replace an element
// This will replace "foo" with "baz"
array_replace_at(ar, "baz", 0);

Removing elements

Clone this wiki locally