0

を使用して、リンクされたリストの char ポインターに複数回入力しようとしています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(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ます。機能は同じですが、コーダーの方が読みやすく理解しやすいです。

于 2016-09-16T13:46:14.803 に答える