我试图使用scanf
多次输入链表中的char指针。但每次我输入新的输入,name
在所有字段的变化。
这是我的链表:
struct node {
struct node *next;
int level;
char *name;
};
下面是我的主要函数:
struct node *root = NULL;
while (1) {
char arrays[12];
char *n;
n = arrays;
int i = NULL;
printf("Enter level: ");
scanf("%i", &i);
printf("nEnter name: ");
scanf("%s", arrays);
insert(&root, i, n, compare);
display(root);
}
插入功能:void insert(struct node **head, const int level, char *name, int(*cmp)(struct node *l, struct node *r))
{
struct node *new;
new = malloc(sizeof *new);
new->level = level;
new->name = name;
/* Find the insertion point */
for (; *head != NULL; head = &(*head)->next)
{
if ((*head)->level > level || (*head)->level == level && cmp(*head, new) > 0) { break; }
}
new->next = *head;
*head = new;
}
如果我输入:
input: | expected output: | actual output:
1 smith | 1 john | 1 alice
1 john | 1 smith | 1 alice
3 malek | 2 alice | 2 alice
2 alice | 3 malek | 3 alice
注意:当我在没有scanf
的情况下手动输入数据时,功能按预期工作例如:
insert(&root, 1, "Abbas", compare);
insert(&root, 1, "Calbass", compare);
这一行:
new->name = name;
只是改变指针的值——它不复制字符串。所以链表中的所有元素都指向arrays
。因此,更改arrays
的内容将使它看起来好像列表中的所有元素都被更改了(但它们没有)。
你可能需要:
拷贝字符串(新->名称,名称);
,然后你需要malloc
内存的字符串。
类似:
new = malloc(sizeof *new);
new->level = level;
new->name = malloc(12 * sizeof(char)); // Memory for the string
strcpy(new->name, name); // Copy the input string
顺便说一句:
改变 insert(&root, i, n, compare);
insert(&root, i, arrays, compare);
并删除n
变量。功能是相同的,但编码更容易阅读和理解。
看起来您正在将指向arrays
的指针插入列表中。当你写:
insert(&root, 1, "Abbas", compare);
它的工作,因为没有修改字符串字面值"Abbas",但arrays
的内容被覆盖,每次scanf("%s", arrays);
被执行。考虑将char* name改为char name[12],并将直接读入节点