I have a generic linked-list that holds data of type void* I am trying to populate my list with type struct employee, eventually I would like to destruct the object struct employee as well.
Consider this generic linked-list header file (i have tested it with type 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 -------------------------------------------------------------------------------------- Consider the employee structure
struct employee { char name[20]; float wageRate; } Now consider this sample testcase that will be called from 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); } Why does the answer that I posted below solve my problem? I believe it has something to do with pointers and memory allocation. The function Malloc() that i use is a custom malloc that checks for NULL being returned.
Here is a link to my entire generic linked list implementation: https://codereview.stackexchange.com/questions/13007/c-linked-list-implementation
emp->name = "Dan";???? Shouldn't it bestrcpy(emp->name, "Dan")?