Mr. Cactus
Mr. Cactus

Reputation: 21

change the value of a string in a linked list

I'm a beginner with regards to C, I hope someone can help me. So, I've been trying to change the value of the string name to another value but when the list is printed the value of the string doesn't change when I input the value with scanf. If I, for example, insert the the value manually like this with the function push(&head, "Carlos") the value of name changes.

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

struct Node{
    char *name;
    struct Node *next;
};


void printList(struct Node *n){
    while (n != NULL){
        printf(" name: %s \n ", n->name);
        printf("....................................\n");
        n = n->next;
    }
}

void push(struct Node **head_ref,  char *name){
    struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
    new_node->name = name;

    new_node->next = (*head_ref);

    (*head_ref) = new_node;
}

int main(){
    struct Node *head = NULL;

    char name[20];

    printf("Insert a name");
    scanf("%s", name);

    push(&head, name);

    printf("Insert a new name");
    scanf("%s", name);

    push(&head, name);

    push(&head, "Carlos");


    printList(head);

    return 0;
}

If I input two names like this : "nadia", "pedro" the output would be this:

    Output:

    Carlos
    ....................................
    pedro
    ....................................
    pedro
    ....................................

The result I want it would be like this :

    Output:

    Carlos
    ....................................
    pedro
    ....................................
    nadia
    ....................................

Upvotes: 2

Views: 126

Answers (2)

AdamF
AdamF

Reputation: 2930

You are scanf name from the user to the same buffer! you need to allocate (on the heap or on the stack) another buffer for the next scanf.
see the main:

   int main(){
    struct Node *head = NULL;
    char namex[20];
    char namey[20];
    printf("Insert a name\n");
    scanf("%s", namex);
    push(&head, namex);
    printf("Insert a new name\n");
    scanf("%s", namey);
    push(&head, namey);
    printList(head);

   return 0;
}

Upvotes: 3

Hitokiri
Hitokiri

Reputation: 3699

You should use strcpy for copying string in c. You have to allocate for name in each new_node:

new_node->name = malloc(20*sizeof(char));
if(!new_node->name) {//handle error}
strcpy(new_node->name,name);

I see in your code:

 scanf("%s", name);

You should change to (you can see Disadvantages of scanf):

 scanf("%19s", name);

Or you can use fgets in stead:

fgets(name, sizeof(name), stdin);

Upvotes: 5

Related Questions