【发布时间】:2020-08-12 00:01:33
【问题描述】:
我是 C 的初学者,希望有人能帮助我。所以,我一直在尝试将字符串名称的值更改为另一个值,但是当打印列表时,当我使用scanf 输入值时,字符串的值不会改变。例如,如果我像这样使用函数push(&head, "Carlos") 手动插入值,则名称的值会发生变化。
#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;
}
如果我输入两个这样的名称:“nadia”、“pedro”,输出将是这样的:
Output:
Carlos
....................................
pedro
....................................
pedro
....................................
我想要的结果是这样的:
Output:
Carlos
....................................
pedro
....................................
nadia
....................................
【问题讨论】:
标签: c string linked-list