【发布时间】:2011-01-26 01:25:54
【问题描述】:
问题已在页尾回答。完全有效的代码。
你好,我想用 C 做我在标题中提出的问题,但是,我不知道如何完成它。由于模板,我在 C++ 中完成了这项工作,但 à la C。这是功能齐全的 C++ 代码:List.h (simple database)
*我现在想知道是否可以使用 void 指针来模拟代码。问题是我看到一个链接指出应该避免使用 void *,因为它可能造成的麻烦比它所能解决的要多。
基本上它是一个存储指向变量本身的指针的“智能数组”。 如果我知道每个指针的大小和指向的每个结构的大小,那么简单的 malloc 和 realloc 应该可以吗?
typedef struct
{
void **list;
// internal
int last_item_index;
size_t element_size; // size of each pointer
int elements; // number of currently allocated elements
int total_size; // >= #elements so that we don't have to always call malloc
int tweak_request_size; // each time the list grows we add this # of elements
} List;
// a shot at an addCopy function
// it deepcopies the object you pass in
List_addCopy(List *db, void *ptr_to_new_element)
{
... // grow **list
// alloc and copy new element
db->list[db->last_item_index+1] = malloc(element_size); // WORKS?
// HOW TO COPY THE ELEMENT TO HERE IF IT IS A STRUCTURE FOR INSTANCE???
...
}
or
// a shot at an assign function
// (allocate the elements yourself then pass the pointer to the List)
List_assign(List *db, void *ptr_to_new_element)
{
db->List = realloc(db->List, element_size*(elements+tweak_request_size));
db->List[db->last_item_index+1] = ptr_to_new_element;
}
// Usage example
List db; // our database
struct funky *now = (funky*)malloc(sizeof(funky));
funky->soul = JamesBrown;
List_addCopy(db, funky);
if (list[0]->soul == JamesBrown)
puts("We did It! :D");
如果我将所有内容分配到外部并仅将指针传递给列表,我想唯一的问题是 void **。
List_add 可能吗?仅使用执行元素分配和/或复制它的回调?
List_assign 可能吗?我不想做很多工作,最终得到不可靠的软件。
非常感谢并为写作中的卷积感到抱歉:p
【问题讨论】:
-
如果你知道元素的大小,并且它是一个简单、扁平的数据结构(没有指向任何需要复制的东西的指针),只需
memcpy结束。 -
@Pemdas:我相信我确实提到过。
-
这不会造成问题吗?使用 void * * ?我看到一个帖子说 void * * 应该避免,因为结果可能会混合:c-faq.com/ptrs/genericpp.htmlThanks