0

ノードに文字列と次のノードへのポインタがある単一リンクリストを作成しています。リンクされたリストの前に挿入する関数を作成しました。問題は、リンクされたリストに新しい値を挿入するたびに、すべてのノードの値が変更されることです。どこが間違っているのかわかりません。助けてください。ここにコードがあります

#include <stdio.h>
#include <stdlib.h>

typedef struct Elem {
char *word;
struct Elem *next;
} Elem;

void printList (Elem **list)
{
if(!(*list)){
    printf("List is empty");
    return ;
}
Elem *curr;
curr = *list;
while(curr)
{
    printf("%s -- ",(curr)->word);
    curr = (curr)->next;
}
}

void insert_in_front(Elem **list, char *value)
{
if(!*list)
{
    printf("List is empty... creating first node\n");
    (*list) = (Elem*) malloc(sizeof(Elem));
    (*list)->word = value;
    (*list)->next = NULL;
    return ;
}

printf("The word in list is %s\n",(*list)->word);

Elem *curr = (Elem*) malloc(sizeof(Elem));
if(!curr)
    exit(-1);
curr->word = value;
curr->next = (*list);
printf("the address of curr is : 0x%x\n",curr);
(*list) = curr;
printf("the address of list is : 0x%x\n",(*list));
}

int main(void)
{
Elem *newList;
newList = NULL;
char inp[15];
while(1)
{
    printf("Enter the string : ");
    scanf("%s",&inp);
    printf("input is %s",inp);
    printf("\nthe address of newList is : 0x%x\n",newList);


    insert_in_front(&newList, &inp);
    printf("the address of newList is : 0x%x\n",newList);
    printList(&newList);
    printf("the address of newList is : 0x%x\n",newList);
    printf("\n");
}
return 0;
}

コードをコピーして貼り付けて実行できます。出力は次のとおりです: デバッグ メッセージを許してください。各挿入後にポインターが新しい場所を指しているかどうかを確認したかっただけです。

Enter the string : hello
input is hello
the address of newList is : 0x0
List is empty... creating first node
the address of newList is : 0x251b010
hello -- the address of newList is : 0x251b010

Enter the string : world
input is world
the address of newList is : 0x251b010
The word in list is world
the address of curr is : 0x251b030
the address of list is : 0x251b030
the address of newList is : 0x251b030
world -- world -- the address of newList is : 0x251b030

Enter the string : testing
input is testing
the address of newList is : 0x251b030
The word in list is testing
the address of curr is : 0x251b050
the address of list is : 0x251b050
the address of newList is : 0x251b050
testing -- testing -- testing -- the address of newList is : 0x251b050

Enter the string : 

前もって感謝します!

4

1 に答える 1

4

問題は、すべてを単一の変数に設定していることです-inp

コピーを作成するのではなく、各ノードが同じアドレスを指すようにします。後続のscanf呼び出しでそれを変更すると、すべてのノードが指すものが変更されます。

strdup などを使用してコピーを作成し、新しいコピーinpに割り当てます。->wordたとえば、次のように言えます。

    insert_in_front(&newList, strdup(inp));

後で解放することを忘れないでください!

ヒント: printList に double ポインターを渡す必要はありません。何も変更するつもりはないので、二重ポインターを渡すと、間違ったことを実行して、関数のスコープ外のリストへのヘッド ポインターを実際に変更することができます。また、関数内のコードが理解しにくくなります。それを単一のポインターに変更し、すべての逆参照を取り除きcurrます。また、トップレベルの実際のリストポインターではなくポインターの単なるコピーであるため、を取り除き、リストを使用して反復することもできます。

于 2013-06-09T06:54:56.357 に答える