Skip to content
Snippets Groups Projects
Commit 7c6c9e78 authored by Bruce Cowan's avatar Bruce Cowan
Browse files

Add array_foreach

parent b6e8fe8d
No related branches found
No related tags found
No related merge requests found
Pipeline #2639 passed
/*
* SPDX-FileCopyrightText: 2018 Bruce Cowan <bruce@bcowan.me.uk>
* SPDX-FileCopyrightText: 2018, 2019 Bruce Cowan <bruce@bcowan.me.uk>
*
* SPDX-License-Identifier: Apache-2.0
*/
......@@ -296,3 +296,19 @@ array_sort (Array *array,
{
qsort (*array->data, array->length, sizeof (void *), func);
}
/**
* array_foreach:
* @array: An array
* @func: A function to run on each element of the array
*
* Run a function on each element of the array
*/
void
array_foreach (Array *array,
ForEachFunc func,
void *user_data)
{
for (size_t i = 0; i < array->length; i++)
(*func) (array->data[i], user_data);
}
......@@ -35,5 +35,8 @@ size_t array_get_length (const Array *array);
size_t array_get_capacity (const Array *array);
// Misc
void array_sort (Array *array,
CompareFunc func);
void array_sort (Array *array,
CompareFunc func);
void array_foreach (Array *array,
ForEachFunc func,
void *user_data);
......@@ -4,16 +4,29 @@
* SPDX-License-Identifier: Apache-2.0
*/
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <array.h>
static void
print_element (void *data,
void *user_data)
{
printf ("%" PRIdPTR " ", (intptr_t) data);
}
static void
print_details (Array *arr)
{
size_t len = array_get_length (arr);
size_t capacity = array_get_capacity (arr);
printf ("Array length %zu, Array capacity %zu\n", len, capacity);
printf ("Data is: ");
array_foreach (arr, print_element, NULL);
printf ("\n");
}
int
......@@ -24,7 +37,7 @@ main (void)
for (int i = 0; i < 10; i++)
{
array_add (arr, NULL);
array_add (arr, (const void *) (intptr_t) i);
print_details (arr);
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment