c语言链表编程有关问题,实在找不到bug,求帮忙
c语言链表编程问题,实在找不到bug,求帮忙
我编写了一个链表,想用来存储学生信息,使用的头插法。运行结果很奇怪,编译没问题,但就是找不到bug,代码如
下:
#include <stdio.h>
#include <string.h>
typedef struct Info
{
int num;
char name[10];
int age;
char sex;
struct Info *next;
}StuInfo;
typedef StuInfo *InfoList;
InfoList Creater();
void main()
{
InfoList newlist = Creater();
}
InfoList Creater()
{
InfoList head;
StuInfo *p, *tail;
head = NULL;
tail = NULL;
p = (InfoList)malloc(sizeof(StuInfo));
if (!p)
{
printf("No memory left.");
return head;
}
printf("Num: ");
scanf("%d",*(p->num));
while(p->num[0])
{
printf("Name: ");
scanf("%s",&(p->name));
printf("Age: ");
scanf("%d",&(p->age));
printf("Sex: ");
scanf("%c",&(p->sex));
if (head == NULL)
head = p;
else
tail->next = p;
tail = p;
p = (InfoList)malloc(sizeof(StuInfo));
if (!p)
{
printf("No memory left");
goto endwhile;
}
printf("Num: ");
scanf("%d",*(p->num));
}
endwhile:if (tail)
tail->next = NULL;
return (head);
}
希望有人能够指点迷津,小弟将不胜感激。
------解决方案--------------------
我编写了一个链表,想用来存储学生信息,使用的头插法。运行结果很奇怪,编译没问题,但就是找不到bug,代码如
下:
#include <stdio.h>
#include <string.h>
typedef struct Info
{
int num;
char name[10];
int age;
char sex;
struct Info *next;
}StuInfo;
typedef StuInfo *InfoList;
InfoList Creater();
void main()
{
InfoList newlist = Creater();
}
InfoList Creater()
{
InfoList head;
StuInfo *p, *tail;
head = NULL;
tail = NULL;
p = (InfoList)malloc(sizeof(StuInfo));
if (!p)
{
printf("No memory left.");
return head;
}
printf("Num: ");
scanf("%d",*(p->num));
while(p->num[0])
{
printf("Name: ");
scanf("%s",&(p->name));
printf("Age: ");
scanf("%d",&(p->age));
printf("Sex: ");
scanf("%c",&(p->sex));
if (head == NULL)
head = p;
else
tail->next = p;
tail = p;
p = (InfoList)malloc(sizeof(StuInfo));
if (!p)
{
printf("No memory left");
goto endwhile;
}
printf("Num: ");
scanf("%d",*(p->num));
}
endwhile:if (tail)
tail->next = NULL;
return (head);
}
希望有人能够指点迷津,小弟将不胜感激。
------解决方案--------------------
- C/C++ code
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct Info { int num; char name[10]; int age; char sex; struct Info *next; }StuInfo; typedef StuInfo *InfoList; InfoList Creater(); void main() { InfoList newlist = Creater(); } InfoList Creater() { InfoList head; StuInfo *p, *tail; head = NULL; tail = NULL; p = (InfoList)malloc(sizeof(StuInfo)); if (!p) { printf("No memory left."); return head; } printf("Num: "); scanf("%d",&(p->num)); while(p->num>0) { printf("Name: "); scanf("%s",(p->name)); printf("Age: "); scanf("%d",&(p->age)); getchar(); printf("Sex: "); scanf("%c",&(p->sex)); p->next = NULL; if (head == NULL) { head = p; tail = p; } else { tail->next = p; tail = p; } p = (InfoList)malloc(sizeof(StuInfo)); if (!p) { printf("No memory left"); goto endwhile; } printf("Num: "); scanf("%d",&(p->num)); } endwhile:if (tail) tail->next = NULL; return (head); }