首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

调试也会过,执行的时候.

2013-06-26 
调试也能过,执行的时候..# include stdio.h# include conio.hstruct student{int numint scorestruc

调试也能过,执行的时候..
# include "stdio.h"
# include "conio.h"
struct student
{
int num;
int score;
struct student* next;
};
typedef struct student STU;
STU* creat (void)
{
STU* head=NULL;
STU* tail=NULL;
head=(STU*)malloc(sizeof(STU));
if (head==NULL)
{
     printf("头结点申请失败:");
     return NULL;
}
head ->next=NULL;
tail=head;
STU* pNewElement=NULL;
int n,s;
while(1)
{
printf("请输入学生学号和成绩:");
    scanf("%d%d",&n,&s);
if(n>0&&s>0)
{
  pNewElement=(STU*)malloc(sizeof(STU));
  if (pNewElement=NULL)
        {
   printf("头结点申请失败:");
   return NULL;
 }
      pNewElement->num=n;
      pNewElement->score=s;
      pNewElement->next=NULL;
      tail->next=pNewElement;
      tail=pNewElement;
    }
  else
  break;
      }
  pNewElement=head;
  head=head->next;
  free(pNewElement);
  return head;
}
void disp(STU* head)
{
    STU* p=head;
    while(1)
    {
        if(p==NULL)
            return;
        printf("(num:%d,score:%d\n",p->num,p->score);
        p=p->next;
    }
}
void main(void)
{
    STU* head=NULL;
    head=creat();
    disp(head);
    getch();
}
接收一个输入以后弹出:这是怎么回事?调试也会过,执行的时候. 链表 调试
[解决办法]

# include <stdio.h>
# include <conio.h>

struct student
{
int num;
int score;
struct student* next;
};

typedef struct student STU;

STU* creat (void)
{
STU* head=NULL;
STU* tail=NULL;
STU* pNewElement=NULL;
int n,s;

head=(STU*)malloc(sizeof(STU));
if (head==NULL)
{
 printf("头结点申请失败:");
 return NULL;
}

head ->next=NULL;
tail=head;

while(1)
{
printf("请输入学生学号和成绩:");
scanf("%d%d",&n,&s);
if(n>0&&s>0)
{
pNewElement=(STU*)malloc(sizeof(STU));
//if (pNewElement=NULL)  //楼主太不小心了,这里用的是等号“==”而不是复制符号“= ”


if(NULL == pNewElement)  //建议楼主以后用“==”这样写,防止出错
{
printf("头结点申请失败:");
return NULL;
}
pNewElement->num=n;
pNewElement->score=s;
pNewElement->next=NULL;
tail->next=pNewElement;
tail=pNewElement;
}
  else
break;
}
pNewElement=head;
head=head->next;
free(pNewElement);
return head;
}

void disp(STU* head)
{
    STU* p=head;
    while(1)
    {
        if(p==NULL)
            return;
        printf("(num:%d,score:%d\n",p->num,p->score);
        p=p->next;
    }
}

void main(void)
{
    STU* head=NULL;
    head=creat();
    disp(head);
    getch();
}


[解决办法]
if (pNewElement=NULL)语句不对,应该是if (pNewElement==NULL),似乎还少一个头文件<stdlib.h>

热点排行