i want to define dynamic array which i don't want to give it constant length ex: uint16_t array1[10]
.
need to dynamically grow when we insert new item.
i want it suitable with TinyOs 1.x
AFAIK, TinyOS does not support dynamic memory allocation. A workaround can be calling libc
functions which are implemented for the AVR and MSP chips.
You'll have to give it a constant length. If you don't like that, then perhaps C isn't the right language for your task.
If you use calloc
, malloc
or realloc
to allocate your array initially, then you can resize it later, using realloc
quite trivially:
#include <stdlib.h>
#include <assert.h>
#include <time.h>
int main(void) {
uint16_t *array = NULL; /* Starts off as NULL, */
size_t length = 0; /* with 0 items. */
srand(time(NULL));
for (size_t x = 0; x < rand(); x++) {
/* This will resize when length is a power of two, eg: 0, 1, 2, 4, 8, ... */
if (length & (length - 1) == 0) {
uint16_t *temp = realloc(array, sizeof *temp * (length * 2 + 1));
assert(temp != NULL); /* todo: Insert error handling */
array = temp;
}
array[length++] = rand();
}
}