我正在制作我的图书馆,当我想到了解指针语法时,我只是感到困惑,在网络上搜索并且变得更加困惑。如何使用C中的指针创建池?
基本上我想打一个游泳池,这里是我真正想做的事:
以下几点必须遵守:
- 当我添加对象到池中,当前数组指向对象的指针是 添加到一个新的指针数组+1(包含新对象)。
- 新阵列由我的foo结构的“对象”指向。
- 旧阵列正在释放。
- 当我打电话的清理功能,在池中的所有对象都 free'd
我应该如何定义我的结构?
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 所有指针任何反馈都会非常受欢迎。
如果C有这种类型的泛型编程,你不觉得[qsort](http://pubs.opengroup.org/onlinepubs/009695399/functions/qsort.html)将使用该函数代替回调函数,并且宽度参数? – Sebivor 2013-03-17 14:58:25
@GrijeshChauhan这本书在第一页说:“只有面向对象允许项目之间的代码重用”。彻底废话!这位作者很困惑。如果没有面向对象的代码重用是不可能的,请在Haskell中解释抽象。 – Sebivor 2013-03-17 15:31:11
看看Ted Jensen的[“C中数组和指针的教程”](http://home.earthlink.net/~momotuk/pointers.pdf),也许可以回顾一下Steve Summit的[“Introductory C programming”] (http://www.eskimo.com/~scs/cclass/cclass.html)。日期,但在问这里之前应该先阅读...... – vonbrand 2013-03-17 16:54:23