我有一个包含 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;
}
现在考虑这个将从 main() 调用的示例测试用例:
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