Banjo API 0.0.1
Multi-purpose C99 API
Loading...
Searching...
No Matches
array.c

Demonstrates how to use the bj_array container, the vector-like structure.

Demonstrates how to use the bj_array container, the vector-like structure.

#include <banjo/api.h>
#include <banjo/array.h>
#include <banjo/log.h>
#include <banjo/main.h>
#include <banjo/memory.h>
int main(int argc, char* argv[]) {
(void)argc;
(void)argv;
bj_array* array = bj_array_new_t(int);
// Add a new element in the array
int a = 42;
bj_array_push(array, &a);
// Get array length
size_t len = bj_array_len(array);
bj_info("Array length: %d\n", len);
// Remove the last element from the array
bj_array_pop(array);
// Clear array
// Clearing the array doesn't change the array memory usage
size_t capacity = bj_array_capacity(array);
bj_info("Capacity: %d", capacity);
// It's possible to reallocate the array so that it only uses the necessary
// space in memory:
capacity = bj_array_capacity(array);
bj_info("Capacity after shrink: %d", capacity);
// Use bj_array_at() to retrieve a value at the given index
int val_0 = 17;
int val_1 = -50;
int val_2 = 101;
bj_array_push(array, &val_0);
bj_array_push(array, &val_1);
bj_array_push(array, &val_2);
int* val = bj_array_at(array, 0); bj_info(".at(0) = %d", *val);
val = bj_array_at(array, 1); bj_info(".at(1) = %d", *val);
val = bj_array_at(array, 2); bj_info(".at(2) = %d", *val);
// You can directly access the array underlying data
int* data = bj_array_data(array);
bj_info("data = [%d, %d, %d]", data[0], data[1], data[2]);
bj_array_del(array);
}
General-purpose definitions for Banjo API.
Header file for Array container type.
void * bj_array_data(const bj_array *array)
Retrieves a pointer to the underlying data of the array.
#define bj_array_new_t(T)
Creates a new bj_array with a payload size inferred from the type T.
Definition array.h:30
struct bj_array_t bj_array
Typedef for the bj_array_t struct.
Definition array.h:21
void bj_array_clear(bj_array *array)
Clears all elements in the array.
void bj_array_push(bj_array *array, const void *value)
Appends a value to the end of the array.
size_t bj_array_capacity(const bj_array *array)
Retrieves the current capacity of the array.
size_t bj_array_len(const bj_array *array)
Retrieves the number of elements in the array.
void bj_array_shrink(bj_array *array)
Shrinks the memory allocation to fit the current array length.
void * bj_array_at(const bj_array *array, size_t at)
Retrieves the value stored at the specified index in the array.
void bj_array_pop(bj_array *array)
Removes the last value from the array.
void bj_array_del(bj_array *p_array)
Deletes a bj_array object and releases associated memory.
#define bj_info(...)
Log a message using the BJ_LOG_INFO level.
Definition log.h:103
Logging utility functions.
All memory-related functions, including custom allocators.