問題在頁面末尾回答。完整的工作代碼。C自動展開式指針陣列
你好,我想在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`即可。 – 2011-01-26 01:30:46
@Pemdas:我相信我確實提到過。 – 2011-01-26 02:33:48