【发布时间】:2016-09-16 13:33:50
【问题描述】:
我正在尝试使用scanf 多次输入链表中的字符指针。但每次我输入新输入时,所有字段中的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);
【问题讨论】:
-
请原谅我的提问,但我认为您的
main()方法中的无限循环永远不会结束。另外,您应该向我们展示insert函数的代码。 -
提供插入和显示功能的代码......
-
@TimBiegeleisen 你是对的,但无限循环仅用于调试目的。
-
scanf("%s", arrays);是一件很糟糕的事情。至少,将其更改为scanf("%11s", arrays);。理想情况下,您希望基于sizeof arrays构建格式字符串
标签: c linked-list char-pointer