A set of macros for managing dynamic arrays in C. These macros simplify operations like creation, resizing, and memory management.
Before using the macros, you need to declare the array type globally using the generate_array_type(type) macro. This should be placed in the global header scope to define the array type structure for the specified type type.
generate_array_type(int);This declares a dynamic array type for int. You can use any valid C type, such as float, double, or custom structs.
Creates a dynamic array of type T with an initial size.
Usage:
Array(int) myArray = array_make(int, 10);Frees the memory of the array.
Usage:
array_free(myArray);Appends a value to the end of the array, resizing if necessary.
Usage:
array_push(myArray, 42);Returns a pointer to the first element of the array.
Usage:
int *start = array_start(myArray);Returns a pointer to the last element of the array.
Usage:
int *end = array_end(myArray);Accesses the element at a specific index.
Usage:
int value = array_at(myArray, 2);Returns the number of elements in the array.
Usage:
usize length = array_length(myArray);Iterates over each element in the array.
Usage:
array_for_each(myArray, el)
{
printf("%d\n", *el);
}#include <stdio.h>
#include <stdlib.h>
// Assuming macros are included
// Declare the array type globally
generate_array_type(int);
int main()
{
Array(int) myArray = array_make(int, 5); // Create array
array_push(myArray, 10); // Add values
array_push(myArray, 20);
array_push(myArray, 30);
array_for_each(myArray, el) // Print values
{
printf("%d\n", *el);
}
array_free(myArray); // Free memory
return 0;
}- Ensure sufficient memory when resizing arrays.
- Handle memory allocation failures with error handling.
- Always free arrays with
array_freeto prevent memory leaks.