【发布时间】:2017-10-25 15:05:57
【问题描述】:
我创建了链接列表来存储员工 ID 和姓名。
当我尝试打印它时,它只显示 id 而不是员工姓名,我还想在用户输入 -1 并且不询问名称时退出程序,它应该简单地退出程序并显示 id 和名称 i目前正在使用 devC++ 编译我的代码
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int id;
char name[20];
struct node *next;
};
struct node *create()
{
struct node *p, *r, *n;
int s, k;
char name[20];
s = sizeof(struct node);
printf("Linked List\n");
printf("Enter id:");
scanf("%d", &k);
printf("Enter name:");
scanf("%s", name);
p = r = NULL;
while(k!=-1)
{
n = (struct node *)malloc(s);
n->id = k;
n->next = NULL;
if(r == NULL)
r = n;
else
p->next=n;
p=n;
printf("Enter the Id or-1 to stop:");
scanf("%d", &k);
printf("Enter the name ");
scanf("%s", name);
}
return(r);
}
void display(struct node *r)
{
printf("\nId Name \n");
while(r != NULL)
{
printf("\n %d", r->id);
printf("\n %s", r->name);
r = r->next;
}
}
int main()
{
struct node *ptr;
ptr = create();
display(ptr);
}
【问题讨论】:
-
你没有存储读取的名字...
-
旁白:你的程序流程很奇怪,因为它让用户在输入退出代码后输入一个名称,-1。
-
请修正代码的缩进。
-
我试图保存名称 n->name=name 但它显示错误
-
你需要使用
strcpy或类似的东西来复制一个字符串。
标签: c linked-list