0

我正在尝试使用多次输入到链表中的字符指针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);
4

2 回答 2

1

这一行:

new->name = name;

只需更改指针的值 - 它不会复制字符串。所以链表中的所有元素都会指向arrays. 因此,更改 的内容arrays将使列表中的所有元素看起来都已更改(但实际上并未更改)。

你可能需要:

strcpy(新->名称,名称);

然后你还需要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变量。功能相同,但编码器更易于阅读和理解。

于 2016-09-16T13:46:14.803 回答
0

看起来您正在将指针插入arrays到列表中。当你写:

insert(&root, 1, "Abbas", compare);

这是有效的,因为没有修改字符串文字“Abbas”,但arrays每次scanf("%s", arrays);执行时都会覆盖 ' 的内容。考虑将 char* name 更改为 char name[12] 并将输入直接读取到节点中。

于 2016-09-16T13:47:09.710 回答