George Francis George Francis - 1 month ago 15
C Question

Error inserting string at the beginning of a Linked List

I have been trying to write a program which inserts a string into the beginning of the linked list, however there has been a slight problem in it. My code is the following.

#include <stdio.h>
#include <stdlib.h>

struct node{
char* data;
struct node* next;
};



void insIni(struct node** hp, char* x){
struct node* tmp = (struct node *)malloc(sizeof(struct node));
tmp->data = x;
tmp->next = *hp;
*hp = tmp;
}

void printList(struct node* h){
struct node* tmp = h;
printf("\nList contents: \n");
while (tmp != NULL){
printf("%s, ", tmp->data );
tmp = tmp->next;
}
printf("\n");
}

int main(int argc, char const *argv[]){

struct node* head = NULL;

char word [256];
scanf("%s", word);
insIni(&head, word);
scanf("%s", word);
insIni(&head, word);
scanf("%s", word);
insIni(&head, word);

printList(head);

return 0;
}


After I insert a new string at the beginning of the linked list, the previous elements are also changed to be the same as the string that has just been insterted, how can I change my code so that the previous elements of the linked list stay the same and only the element at the beginning is added?

For example, if I write A B C, the Linked List ends up being printed as C, C, C, instead of C, B, A,.

Answer

The value you pass to insIni is always the same so all nodes will point to the same. What you need to do is a copy of the data.

E.g.

void insIni(struct node** hp, char* x){
    struct node* tmp = (struct node *)malloc(sizeof(struct node)); 
    tmp->data = strdup(x);
    tmp->next = *hp;
    *hp = tmp;
}

or

char *p = malloc(strlen(x)+1);
strcpy(p, x);
tmp->data = p;