我想定义动态array,我不想给它固定的长度,例如:uint16_t array1[10]。
需要动态增长时,我们插入新的项目。
我想让它适用于TinyOs 1.x
发布于 2013-04-24 18:56:55
AFAIK,TinyOS不支持动态内存分配。一种解决方法是调用为AVR和MSP芯片实现的libc函数。
发布于 2013-04-16 12:03:47
你必须给它一个恒定的长度。如果你不喜欢这一点,那么C语言可能不适合你的任务。
如果最初使用calloc、malloc或realloc来分配数组,则可以稍后使用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();
}
}https://stackoverflow.com/questions/16028258
复制相似问题