#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void Insert();
void DisplayList();
struct Student
{
char Name[10];
int Marks;
struct Student *Next;
} *Start;
int main()
{
Start = NULL;
int Choise;
while (1)
{
printf("enter number to choose ");
scanf_s("%d", &Choise);
switch (Choise)
{
case 1:
Insert();
break;
case 3:
DisplayList();
break;
default:
printf("Incorrect assignment Press relevant key :");
}
}
}
void Insert()
{
struct Student *Temp, *current=NULL;
Temp = (struct Student *) malloc(sizeof(struct Student));
printf("Enter Name Of Student");
scanf_s("%s",&Temp->Name);
printf("Enter Marks Of Student");
scanf_s("%d", &Temp->Marks);
Temp->Next = NULL;
if (Start == NULL)
{
Start = Temp;
Temp->Next = NULL;
}
else
current = Start;
while (current->Next != NULL)
{
current = current->Next;
current->Next = Temp;
}
}
void DisplayList()
{
struct Student *current, *Temp;
current = Start->Next;
if (Start == NULL)
{
printf("No Element in the list");
}
else
{
for (current = Start; current != NULL; current = current->Next)
{
printf("The List are\n");
printf_s("%d",current->Marks);
}
}
这是为单个链表编写的程序。当我显示列表时,它只给出列表中的一个元素。每当我尝试打印链表的元素时,它只给输出一个元素 我做了什么错误请帮忙?
答案 0 :(得分:1)
变化
else
current = Start;
while (current->Next != NULL)
{
current = current->Next;
current->Next = Temp;
}
到
else {
current = Start;
while (current->Next != NULL)
{
current = current->Next;
}
current->Next = Temp;
}
和
scanf_s("%s", Temp->Name, sizeof(Temp->Name)); //remove & and add size(see Amnon's answer)
答案 1 :(得分:1)
当使用scanf_s
这是scanf的安全版本时,您不仅要传递缓冲区的地址,还要传递它的大小作为下一个参数,即:
scanf_s("%s", Temp->Name, _countof(Temp->Name));
您可以在http://msdn.microsoft.com/en-us/library/w40768et.aspx
中详细了解相关信息代码的另一个问题是,您使用current
初始化NULL
,然后尝试访问其Next
字段。
答案 2 :(得分:0)
在此更改代码:
else
current = Start;
while (current->Next != NULL)
{
current = current->Next;
current->Next = Temp;
}
到此:
else {
current = Start;
while (current->Next != NULL)
{
current = current->Next;
}
current->Next = Temp;
temp->next=NULL;
}
你忘记在下一个指针处添加NULL,因此你只得到单个输出。