Implementation dynamic array without depend the stored type. Object of type da_t
save information about stored type (size and destruction function). When creating new da
need set size of stored type and destructor if necessary.
DA_CREATE_VAR(da, int, NULL); // place 'da' to stack
/* ... some code ... */
size_t length = da.count; // access to field
da_some_func(&da, ...);
da_at_fwd
- get pointer to item by index as return valueda_at
- get pointer to item by indexda_front
- get pointer to first itemda_back
- get pointer to last item
da_insert
- insert value from pointer into position by indexda_insert_imm
- insert value into position by indexda_insert_many
- insert values from array into position by indexda_push_back
- insert value from pointer into last positionda_push_back_imm
- insert value into last positionda_push_back_many
- insert value from array into last position
da_remove
- remove item by indexda_remove_many
- remove items by indexes in rangeda_pop_back
- remove last itemda_pop_back_many
- remove N-last items
da_clear
- remove all items and save capacityda_destroy
- remove all items and free allocated memory
da_reserve
- reserve memory for N-itemsda_shrink_to_fit
- deallocate free capacity
DA_IMPLEMENTATION
- add definition of functionsDA_DEF
- User-provided attributes (as an example:__declspec(dllexport)
)DA_INIT_CAP
- default start capacity for emptyda
DA_CREATE_VAR
- initialize new variable of typeda_t
DA_FOREACH
- expand to header (for
with brackets) for for-loop and iterable byda
DA_VOID_FOREACH
- asDA_FOREACH
, but usevoid *
iterator variable
Print command line arguments
#define DA_IMPLEMENTATION
#include "common_da.h"
#include <stdio.h>
int main(int argc, char** argv) {
DA_CREATE_VAR(args, const char*, NULL);
da_error_t err;
err = da_push_back_many(&args, argv, argc);
if (err != dae_success) { // error check
fprintf(stderr, "%s\n", da_error_to_str(err));
return 1;
}
size_t i = 0;
printf("argc = %zu\n", args.count);
DA_FOREACH(const char*, arg, &args) {
printf("argv[%zu] = %s\n", i++, *arg);
}
da_destroy(&args);
return 0;
}
Possible output
$ ./main foo bar baz
argc = 4
argv[0] = main.exe
argv[1] = foo
argv[2] = bar
argv[3] = baz