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
....................................