我正在制作我的库,就在我想理解指针语法时,我只是感到困惑,在网上搜索并变得更加困惑。
基本上我想做一个游泳池,这是我真正想做的:
必须遵守以下几点:
- 当我向池中添加一个对象时,当前数组指向对象的指针是 添加到新的指针数组 + 1(以包含新对象)。
- 新数组由我的 foo 结构的“对象”指向。
- 旧阵列正在释放。
- 当我调用清理函数时,池中的所有对象都 免费的
我应该如何定义我的结构?
typedef struct {
int n;
(???)objects
} foo;
foo *the_pool;
这是管理我的池的代码:
void myc_pool_init ()
{
the_pool = (???)malloc(sizeof(???));
the_pool->n = 0;
the_pool->objects = NULL;
}
void myc_push_in_pool (void* object)
{
if (object != NULL) {
int i;
(???)new_pointers;
the_pool->n++;
new_pointers = (???)malloc(sizeof(???)*the_pool->n);
for (i = 0; i < the_pool->n - 1; ++i) {
new_pointers[i] = (the_pool->objects)[i]; // that doesn't work (as I'm not sure how to handle it)
}
new_array[i] = object;
free(the_pool->objects);
the_pool->objects = new_array; // that must be wrong
}
}
void myc_pool_cleanup ()
{
int i;
for (i = 0; i < the_pool->n; ++i)
free((the_pool->objects)[i]); // as in myc_push_in_pool, it doesn't work
free(the_pool->objects);
free(the_pool);
}
注意:添加到池中的对象类型是事先不知道的,所以我应该把所有指针都当作void处理 我们将非常欢迎任何反馈。
最佳答案
您问题的直接答案是:使用 void *
。这种类型非常强大,因为它允许您将任何类型的指针放入您的池中。但是,在从您的池中检索 void *
指针时,是否进行正确的转换取决于您。
你的结构看起来像这样
typedef struct {
int n;
(void **)objects
} foo;
foo *the_pool;
如指针数组。
你的 malloc:
new_pointers = (void **)malloc(sizeof(void *)*the_pool->n);
此处存在性能问题。您可以简单地分配一个固定大小的数组,并且仅在元素数量超过预定义的加载因子(=使用的数量/最大大小)时才重新分配
此外,您可以只使用 realloc
( http://www.cplusplus.com/reference/cstdlib/realloc/ )
the_pool->objects = (void **)realloc(the_pool->objects, the_pool->n* sizeof(void*));
Realoc 尝试增加当前分配的区域,而不需要复制所有内容。只有当函数不能连续增加分配的区域时,它才会分配一个新区域并复制所有内容。
关于c - 如何在 C 中创建一个带指针的池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15462113/