我在 C 中创建了一个简单的动态数组。
typedef struct varray_t
{
void **memory;
size_t allocated;
size_t used;
int index;
} varray;
void
varray_init(varray **array)
{
*array = (varray*) malloc (sizeof(varray));
(*array)->memory = NULL;
(*array)->allocated = 0;
(*array)->used = 0;
(*array)->index = -1;
}
void
varray_push(varray *array, void *data, size_t size)
{
if ((array->allocated - array->used) < size) {
array->memory = realloc(array->memory, array->allocated + size);
array->allocated = array->allocated + size;
}
array->used = array->used + size;
array->memory[++array->index] = data;
}
int
varray_length(varray *array)
{
return array->index + 1;
}
void
varray_clear(varray *array)
{
int i;
for(i = 0; i < varray_length(array); i++)
{
array->memory[i] = NULL;
}
array->used = 0;
array->index = -1;
}
void
varray_free(varray *array)
{
free(array->memory);
free(array);
}
void*
varray_get(varray *array, int index)
{
if (index < 0 || index > array->index)
return NULL;
return array->memory[index];
}
这工作正常。但是要将项目添加到数组中,调用者必须传入要添加的元素的大小。我想不出另一种方法来获取传入的大小void*
。我想知道是否有更好的设计方法varray_push(varray *array, void *data, size_t size)
可以size
推断出来?
任何帮助都会很棒
建议后编辑的代码
我的数组将只包含指针元素。我根据 Blastfurnace 的建议修改了代码。新代码将按sizeof(void*)
常数比例使用和调整内存大小,以在插入时获得摊销的常数时间。
void
varray_push(varray *array, void *data)
{
size_t toallocate;
size_t size = sizeof(void*);
if ((array->allocated - array->used) < size) {
toallocate = array->allocated == 0 ? size : (array->allocated * 2);
array->memory = realloc(array->memory, toallocate);
array->allocated = array->allocated + toallocate;
}
array->memory[++array->index] = data;
array->used = array->used + size;
}