0

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

Hana90
  • 943
  • 5
  • 17
  • 37

2 Answers2

1

AFAIK, TinyOS does not support dynamic memory allocation. A workaround can be calling libc functions which are implemented for the AVR and MSP chips.

Dumbo
  • 13,555
  • 54
  • 184
  • 288
0

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();
    }
}
autistic
  • 1
  • 3
  • 35
  • 80