I got an homework assignment where I need to fill up all the functions. Now when I get into the 3rd print, I get an error that ptr ( variable ) cannot access the data ( before he could? )
I tried printing the values before sending them to the function and see what it gets and it get the right name but the in the function something is messed up
Struct:
typedef struct {
char name[32];
char surname[32];
char id[32];
char position[64];
int salary;
} EmployeeData;
typedef struct tEmployeeNode {
EmployeeData data;
struct tEmployeeNode *next;
} EmployeeNode;
Array with all the data:
EmployeeData data[4] = {
{ "John","Silver","200011123", "Mutineer", 3000 },
{ "David","Livesey","122233345", "Doctor", 7000 },
{ "Jim","Hawkins","201072716", "Cabin Boy", 1000 },
{ "John","Trelawney","122233444", "Squire", 200 } };
Creating Node
EmployeeNode *createEmployeeNode(EmployeeData data) {
EmployeeNode *temp = (EmployeeNode *)malloc(sizeof(EmployeeData));
temp->data = data;
temp->next = NULL;
return temp;
}
Creating a linked list function
EmployeeNode *createListOfEmployees(EmployeeData *arr, int size) {
int i;
EmployeeNode *head, *ptr;
EmployeeNode *temp = (EmployeeNode *)malloc(sizeof(EmployeeData));
if (temp == NULL) {
printf("Error\n");
exit(1);
}
temp->data = arr[0];
temp->next = NULL;
head = temp;
ptr = head;
for (i =1; i < size; i++) {
temp = createEmployeeNode(arr[i]);
if (ptr->next != NULL) {
ptr = ptr->next;
}
else {
ptr->next = temp;
temp->next = NULL;
}
}
return head;
}
main printf function :
void printListOfEmployees(EmployeeNode *head) {
EmployeeNode *ptr = head;
while (ptr != NULL) {
printEmployee(ptr->data);
ptr = ptr->next;
}
}
inside printf function :
void printEmployee(EmployeeData e) {
printf("%s %s %s %s %d\n", e.name, e.surname, e.id, e.position, e.salary);
}
Here is where I'm actually calling the functions
EmployeeNode *head = createListOfEmployees(data, 4);
printf("Employees of the Espaniola Team:\n\n");
printListOfEmployees(head);
The result should be: a. all the array node should be in the Struct with a linked list to the next node and print everything in the right order. Mainly my problem is that I lose "Jim Hawkins" and couldn't figure why.
Thanks for the help!
Correct body of createListOfEmployees
function (without error check for brevity):
EmployeeNode *head= NULL;
EmployeeNode *previousnode = NULL;
for (int i = 0; i < size; i++) {
EmployeeNode *newnode = createEmployeeNode(arr[i]);
if (previousnode != NULL)
previousnode->next = newnode;
else
head = newnode;
previousnode = newnode;
}
return head;
Keep it simple.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.