Luis Lavieri
Luis Lavieri

Reputation: 4129

Building a LinkedList from structs

I'm trying to build a Linkedlist from an array of structs like this:

node * current = NULL, *list= NULL;

current = (node *)malloc(sizeof(node));

current->employee.EMP_ID = ed[0].EMP_ID;
strcpy(current->employee.name, ed[0].name);
current->employee.dept = ed[0].dept;
current->employee.rank = ed[0].rank;
current->employee.salary = ed[0].salary;
current->next = NULL;

list = current;

current = current->next;

for (int i = 1; i < 2; i++){

    node *current = (node *)malloc(sizeof(node));

    current->employee.EMP_ID = ed[i].EMP_ID;
    strcpy(current->employee.name, ed[i].name);
    current->employee.dept = ed[i].dept;
    current->employee.rank = ed[i].rank;
    current->employee.salary = ed[i].salary;
    current->next = NULL;

    list->next = current;

    current = current->next;
}

However, it's only storing the last value from the struct. What can I do?

Upvotes: 0

Views: 37

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40155

try this

node * current = NULL, *list= NULL;

current = (node *)malloc(sizeof(node));

current->employee = ed[0];
current->next = NULL;

list = current;

for (int i = 1; i < 2; i++){

    node *np = (node *)malloc(sizeof(node));

    np->employee = ed[i];
    np->next = NULL;

    current = current->next = np;
}

Upvotes: 1

Related Questions