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
答案 0 :(得分:4)
这是错误的,这是一个奇迹,它的工作原理。您正在读取未定义的地址(错误,错误!!),然后您为所有员工重复使用相同的错误地址。
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指出了其他一些错误,他是对的
create
中的:
else
{
e->dep=temp; // e is not initialized here
e=temp; // now ok
create_e(&e,temp->dname);
}
只删除e->dep=temp
,因为它没有功能效果,但写入了单位化内存。