我想定义我不想给它恒定长度 ex:的动态数组uint16_t array1[10]。
当我们插入新项目时需要动态增长。
我希望它适用于 TinyOs 1.x
AFAIK,TinyOS 不支持动态内存分配。一种解决方法是调用libc为 AVR 和 MSP 芯片实现的函数。
你必须给它一个恒定的长度。如果您不喜欢这样,那么 C 语言可能不适合您的任务。
如果您使用calloc, mallocorrealloc最初分配您的数组,那么您可以稍后调整它的大小,使用realloc非常简单:
#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();
    }
}