C ogólna lista powiązana
Mam ogólną listę powiązań, która przechowuje dane typu void * Próbuję zapełnić moją listę typem struct employee, w końcu chciałbym również zniszczyć obiekt struct pracownik również.
Rozważmy ten ogólny plik nagłówkowy z listą połączoną (przetestowałem go z char charakterem *):
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
--------------------------------------------------------------------------------------
Rozważ strukturę pracowników
struct employee
{
char name[20];
float wageRate;
}
Rozważ teraz przykładową skrzynkę testową, która zostanie wywołana z 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);
}
Dlaczego odpowiedź zamieszczona poniżej rozwiązuje mój problem? Wierzę, że ma to coś wspólnego ze wskaźnikami i alokacją pamięci. Funkcja Malloc (), której używam, to niestandardowy malloc, który sprawdza, czy zwracana jest wartość NULL.
Oto link do mojej całościowej implementacji połączonej listy:https://codereview.stackexchange.com/questions/13007/c-linked-list-implementation