なぜ私の二重リンクリストのC実装が重複した値を作成するのですか?
-
26-10-2019 - |
質問
Cで二重にリンクされたリストの実装をコーディングしました。そのため、値を挿入した後、値の複製が得られています。つまり、すべてのリスト項目で複製された私から与えられた最後の値。
私のコードは次のとおりです
header.h
#include<stdio.h>
#include<stdlib.h>
typedef struct doubly_list
{
int id;
char *name;
struct doubly_list *next;
struct doubly_list *prev;
}node;
void insertfirst(node **,int ,char *);
void insertlast(node **,int ,char *);
doubly_list_insert.c
#include"header.h"
void insertfirst(node **head,int id,char *name)
{
node *tmp=(node *)malloc(sizeof(node));
if(NULL == tmp)
{
printf("\nMemory allocation failed\n");
exit(1);
}
tmp->id=id;
tmp->name=name;
tmp->prev=NULL;
if(*head== NULL)
{
tmp->next=NULL;
*head=tmp;
}
else
{
tmp->next=*head;
(*head)->prev=tmp;
*head=tmp;
}
}
void insertlast(node **head,int id,char *name)
{
if(*head==NULL)
{
insertfirst(head,id,name);
return;
}
node *last=*head;
node *tmp=(node *)malloc(sizeof(node));
if(NULL == tmp)
{
printf("\nMemory allocation failed\n");
exit(1);
}
tmp->id=id;
tmp->name=name;
tmp->next=NULL;
while(last->next!=NULL)
{
last=last->next;
}
last->next=tmp;
tmp->prev=last;
}
doubly_list_traverse.c
#include"header.h"
void traverse(node *head)
{
node *tmp=head;
if(head==NULL)
{
printf("\nList is empty\n");
exit(1);
}
while(tmp!=NULL)
{
printf("%d --> %s\n",tmp->id,tmp->name);
tmp=tmp->next;
}
}
そして、ここにメインファイルがあります、
main.c
#include"header.h"
int main()
{
int choice;
int id;
char name[15];
node *root=NULL;
system("clear");
while(1)
{
printf("\n1.Insert First\n");
printf("\n2.Insert Last\n");
printf("\n3.Traverse\n");
printf("\n4.Exit\n");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the employee id : ");
scanf("%d",&id);
printf("\nEnter the employee name : ");
scanf("%s",name);
insertfirst(&root,id,name);
break;
case 2:
printf("\nEnter the employee id : ");
scanf("%d",&id);
printf("\nEnter the employee name : ");
scanf("%s",name);
insertlast(&root,id,name);
break;
case 3:
traverse(root);
break;
case 4:
return 0;
break;
default:
printf("\nPlease enter valid choices\n");
}
}
}
実行中、最初に1つのデータのみを挿入する場合、私からの入力が適切に入力されます。
しかし、2番目のものを挿入すると、問題が発生します。私の場合、ID値は同じままです。ただし、2番目の入力の名前値は1番目の値で複製されます。
なぜこれが起こっているのですか?それは議論を渡す際に何か問題ですか?
解決
新しいノードを作成すると、名前にポインターをコピーするだけでノード名を設定します。ポインターではなく文字列をコピーする必要があります。 strdup
機能はこれに最適です:
tmp->name=strdup(name);
覚えておいてください free
ノードを解放したときの名前。
編集
あなたが電話するとどうなりますか insertfirst
初めて、それはそれです name
最初のノードのフィールドはを指します name
配列 main
. 。 2番目のノードの名前を取得すると、配列の内容 main
新しい名前で更新され、最初のノードのポインターがその配列を指しているため、名前が複製されているようです。
所属していません StackOverflow