我是一名有用的助手,可以为您进行翻译。以下是您需要翻译的内容:
我有一个通用的链表,保存void*类型的数据。我想使用struct employee类型的数据填充我的链表,最终我也想析构struct employee对象。
考虑这个通用的链表头文件(我已经测试过它可以使用char*类型):
struct accListNode //the nodes of a linked-list for any data type
{
void *data; //generic pointer to any data type
struct accListNode *next; //the next node in the list
};
struct accList //a linked-list consisting of accListNodes
{
struct accListNode *head;
struct accListNode *tail;
int size;
};
void accList_allocate(struct accList *theList); //allocate the accList and set to NULL
void appendToEnd(void *data, struct accList *theList); //append data to the end of the accList
void removeData(void *data, struct accList *theList); //removes data from accList
--------------------------------------------------------------------------------------
考虑员工结构。
struct employee
{
char name[20];
float wageRate;
}
现在考虑这个将从主函数调用的样本测试用例:
void test2()
{
struct accList secondList;
struct employee *emp = Malloc(sizeof(struct employee));
emp->name = "Dan";
emp->wageRate =.5;
struct employee *emp2 = Malloc(sizeof(struct employee));
emp2->name = "Stan";
emp2->wageRate = .3;
accList_allocate(&secondList);
appendToEnd(emp, &secondList);
appendToEnd(emp2, &secondList);
printf("Employee: %s\n", ((struct employee*)secondList.head->data)->name); //cast to type struct employee
printf("Employee2: %s\n", ((struct employee*)secondList.tail->data)->name);
}
为什么我下面发布的答案解决了我的问题?我相信这与指针和内存分配有关。我使用的函数Malloc()是一个自定义的malloc,它检查是否返回NULL。
这是我整个通用链表实现的链接:https://codereview.stackexchange.com/questions/13007/c-linked-list-implementation