【问题标题】:linked list char pointer scanf input链表 char 指针 scanf 输入
【发布时间】: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


【解决方案1】:

这一行:

new->name = name;

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

你可能需要:

strcpy(new->name, name);

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 2015-06-12
      • 2014-07-23
      • 2015-05-30
      • 1970-01-01
      • 2018-01-03
      相关资源
      最近更新 更多