|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
#include<malloc.h>
struct student
{
int num;
int score;
struct student *next;
};
typedef struct student STU;
STU *create()
{
STU *head = NULL;
STU *tail = NULL;
head = (STU *)malloc(sizeof(STU));
if(head==NULL)
{
printf("头结点申请失败!\n");
return NULL;
}
head->next=NULL;
tail=head;
STU *pNew=NULL;
int n,s;
while(1)
{
printf("请输入学生的学号和成绩:\n");
scanf("%d %d",&n,&s);
if(n>0 && s>0)
{
pNew=(STU *)malloc(sizeof(STU));
if(pNew==NULL)
{
printf("节点内存申请失败!\n");
return NULL;
}
pNew->num=n;
pNew->score=s;
pNew->next=NULL;
tail->next=pNew;
tail=pNew;
}
else
{
break;
}
}
pNew=head;
head=head->next;
free(pNew);
return head;
}
void disp(STU *head)
{
STU *p=head;
while(1)
{
if(p==NULL)
{
return;
}
printf("( 学号:%d , 成绩:%d )\n",p->num,p->score);
p=p->next;
}
}
int main()
{
STU *head=NULL;
head=create();
disp(head);
}
这段代码没错,运行也能达到要求,下边这段代码和上边的相差无几,错也没有,可是就是有问题,
#include<stdio.h>
#include<malloc.h>
struct student
{
int num;
int score;
struct student *next;
};
typedef struct student S;
S *create()
{
S *head = NULL;
S *tail = NULL;
head=(S *)malloc(sizeof(S));
if(head==NULL)
{
printf("头结点内存申请失败!\n");
return NULL;
}
head->next=NULL;
tail=head;
S *neww=NULL;
int n,s;
while(1)
{
printf("请输入学生的学号和成绩:");
scanf("%d %d",&n,&s);
if((n>0) && (s>0))
{
neww=(S *)malloc(sizeof(S));
if(neww==NULL);
{
printf("节点内存申请失败!\n");
return NULL;
}
neww->num=n;
neww->score=s;
neww->next=NULL;
tail->next=neww;
tail=neww;
}
else
{
break;
}
}
neww=head;
head=head->next;
free(neww);
return head;
}
void disp(S *head)
{
S *p=head;
while(1)
{
if(p==NULL)
{
return;
}
printf("( 学号:%d , 成绩:%d )\n",p->num,p->score);
p=p->next;
}
}
int main()
{
S *head=NULL;
head=create();
disp(head);
}
这段代码在head指针申请内存那里申请失败,程序直接终止了,到底出了什么问题?
|
|