C родовой связанный список
У меня есть общий связанный список, содержащий данные типа void * Я пытаюсь заполнить свой список структурой типа employee, в конце концов я бы также хотел уничтожить объект object 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