如果您想要一个完全通用的函数,它将对象数组设置为某个“模板”对象指定的值,您可以使用如下函数:
void init_array( void* arr, size_t nmemb, size_t size, void const* initializer)
{
size_t i = 0;
char* p = (char *) arr;
for (i = 0; i < nmemb; ++i) {
memcpy( p, initializer, size);
p += size;
}
}
然后您的分配/初始化代码可能如下所示:
typedef void* slot_t;
static const slot_t empty_slot = NULL; // or make this a global if that
// works better for your scenario
int n = 10;
// note: your original `malloc()` line:
//
// slot_t slots[] = (slot_t[])malloc(sizeof(slot_t)*n)
//
// wouldn't work, as you can't assign to an array as a whole.
// That line shouldn't even compile.
slot_t* slots = (slot_t*)malloc(sizeof(slot_t)*n);
// completely generic initialization
init_array( slots, n, sizeof(slot_t), &empty_slot);
如果你想初始化一个指针数组,你可以有另一个函数更直接地处理这种情况:
void init_ptr_array( void* arr, size_t nmemb, void* initializer)
{
size_t i = 0;
void* p;
for (; p < arr + nmemb; ++p) {
*p = initializer;
}
}
// arrays of object pointers
init_ptr_array( slots, n, empty_slot);
我不确定我是否喜欢这两个函数对最后一个参数的含义略有不同。如果我的程序中需要这两种初始化,我可能会坚持使用通用的初始化指针数组。它可能效率较低,但初始化通常不是瓶颈。