gpt4 book ai didi

c - 链接列表没有给出所需的输出

转载 作者:太空宇宙 更新时间:2023-11-04 06:19:02 25 4
gpt4 key购买 nike

void create_e(struct department **,char *);
void create(struct department **s,char *str)
{ struct department *temp,*e;
temp=(struct department *)malloc(sizeof(struct department));
temp->dname=str;
temp->dep=NULL;
temp->emp=NULL;
if(*s==NULL)
{
*s=temp;
e=temp;
create_e(&e,temp->dname);

}
else
{
e->dep=temp;
e=temp;
create_e(&e,temp->dname);
}
}
void create_e(struct department **s,char *str)
{int x,i;
printf("enter the employee details of %s \n",str);
printf("enter the no of employee:");

scanf("%d",&x);

for(i=0;i<x;i++)
{
struct employee *temp1,*e1;
temp1=(struct employee *)malloc(sizeof(struct employee));
char *name;
printf("enter emp name:");
scanf("%s",name);
temp1->ename=name;
int age,salary;
printf("enter age:");
scanf("%d",&age);
printf("enter salary:");
scanf("%d",&salary);

temp1->age=age;
temp1->salary=salary;
temp1->next=NULL;
if((*s)->emp==NULL)
{
(*s)->emp=temp1;
e1=temp1;
}
else
{
e1->next=temp1;
e1=temp1;
}
}
}

这是一个链表中链表的程序,第一个链表是部门,其结构是

      struct department
{
char *dname;
struct department *dep;
struct employee *emp;
}

第二个是员工的姓名、年龄和薪水

   struct employee
{
char *ename;
int age;
int salary;
struct employee *next;
};

我的问题是显示链接列表。除了员工姓名外,其他一切都显示得很好。最后一个部门的最后一名员工的姓名显示在所有其他员工姓名的位置。显示功能很好我已经尝试过其他程序。例如,输出应该是:

maths->john|23|20->ron|24|25
sci->harry|19|8->chris|21|40

但是输出结果是:

maths->chris|23|20->chris|24|25
sci->chris|19|8->chris|21|40

最佳答案

这是错误的,奇迹般地起作用了。您正在读取未定义的地址(错误,错误!!),然后您为所有员工重复使用相同的错误地址。

  char *name;  // undefined, unallocated
printf("enter emp name:"); // this is correct :)
scanf("%s",name); // scanf just stores the name here, in the woods
temp1->ename=name; // you copy the unitialized pointer with correct data, which gets overwritten each time

如果你声明:char *name = NULL; 它会立即崩溃(实际上会更好)

写:

  char name[100]; // properly allocated buffer on the stack
printf("enter emp name:");
scanf("%99s",name); // truncates if more than 99: safety
temp1->ename=strdup(name); // allocate the right amount of memory & copy string

编辑:BLUEPIXY 指出了其他一些错误,他是对的

创建中:

else
{
e->dep=temp; // e is not initialized here
e=temp; // now ok
create_e(&e,temp->dname);
}

只需删除 e->dep=temp,因为它没有任何功能影响,但会写入单元化内存。

关于c - 链接列表没有给出所需的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39317770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com