请问这段C程序是哪有问题

[复制链接]
查看11 | 回复1 | 2009-7-22 15:18:16 | 显示全部楼层 |阅读模式
请问下面这段c程序是哪有问题
#include
#include
#define LEN sizeof(struct xuesheng);
struct xuesheng
{

long xuehao;

float chengji;

struct xuesheng *next;
};
int main(void)
{

struct xuesheng *p1,*p2,*head;

int n;

head=NULL;

p1=p2=(struct xuesheng *)malloc(LEN);

scanf("%ld %f",p1->xuehao,p2->chengji);

while(p1->xuehao!=0)

{

++n;

if(n==1) head=p1;

else p2->next=p1;

p2=p1;

p1=(struct xuesheng *)malloc(LEN);

scanf("%ld %f",p1->xuehao,p1->chengji);

}

p2->next=NULL;

return 0;
}

回复

使用道具 举报

千问 | 2009-7-22 15:18:16 | 显示全部楼层
问题多多:1、把此行#define LEN sizeof(struct xuesheng);末尾的分号去掉2、变量n定义后并没有赋初始值,就进行了++n的操作3、程序结束时,p1指向的结构是无效的,但没有释放分配的内存4、这个以head开头的单向链表没有释放内存,内存泄露了。建议:1、head的赋值不必在循环中,在循环外赋值比较好2、xuehao和chengji的读取,可以考虑先读取到普通变量中,在判断后再分配结构内存,建立新链表。...
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行