First problem: Good ... you didn’t specify an employee type ad. I assume the first and last are declared as char pointers, and this is a mistake. You need them to be a fixed char array size, or this will never work. Select the maximum length for the string and declare the structure as follows.
typedef struct { char name[50]; char surname[50]; .... } employee;
Previous Post:
Well, I have to admit that I don't like this way of implementing things. I would use a more stable approach.
First of all, since this is just a list of items, you can use a doubly linked list. This will allow you to add and remove elements with O (1) complexity. Very good indeed.
It will also allow you to iterate over all elements from first to last.
For this, I would use a more OOP-oriented approach. I know we are in C, but listen to this idea.
typedef struct { MyList* OwnerList; Employee* Previous; Employee* Next; char name[50]; int age; } Employee; typedef struct { Employee* First; Employee* Last; int Count; } MyList; MyList* AllocList() { return calloc(sizeof(MyList), 1); } void DeleteList(MyList* list) { Employee* current; Employee* next; for (current = list->First; current != NULL; current = next) { next = current->Next; free(current); } free(list); } int GetCount(const MyList* list) { return list->Count; } Employee* AddAmployee(MyList* list) { Employee* result = calloc(sizeof(Employee), 1); Employee* last = list->Last; if (last != null) last->Next = result; else list->First = result; result->Previous = last; list->Last = result; ++list->Count; result->OwnerList = list; return result; } void RemoveEmployee(Employee* employee) { free(employee); }
Now for iteration, all elements are simple:
Employee* current; for (current = list->First; current != null; current = current->Next) printf("%s %d\n", current->name, current->age);
source share