user1234567 user1234567 - 1 year ago 91
C Question

How to pass two parameters in a linked list node using c?

I am learning how to use structure with linked list in c. So I was trying to keep inserting the node to first position. Also, each node contains two different kinds of values, one is char array and another one is integer. Once I insert a value, then print the current list out. I look over and over again but I can't find where gets something wrong because I set a printf() test in the insert function. I saw the new_node is what I currently insert.

When I insert a 1 first and it prints out a/1. But I am so confusing when I insert another set such as b 2, it prints out



which means the name of first node changed along with inserting a new node, but the numbers did not change. Can anyone see what happened here?

struct node{
char *name;
int numbers;
struct node *next;
struct node *list = NULL;

void printList(struct node *node){
while (node != NULL){
printf("%s/%d\n", node->name, node->numbers);
node = node->next;

void insert(struct node **list, char *name, int numbers){
struct node * new_node = malloc(sizeof(struct node));
new_node->name = name;
new_node->numbers = numbers;
//printf("......%s %d.........\n", new_node->name, new_node->numbers);
new_node->next = *list;
*list = new_node;

int main(){
......code for scanf() are omitted......
insert(&list, name, numbers);

Answer Source

Your problem is that your are pointing on same buffer for every node. Even without seeing the code you removed, I can guess you are reading the node names in same char array. You would better consider using strdup() as it was suggested:

new_node->name = strdup(name);

Make sure you free this pointer when you are destroying the node.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download