动态创建链表哪儿错了?
下面是本人编写的一个动态创建链表的程序,VC6.0编译时没有错,链接时也没有错。但是运行时就会弹出出错窗口,提示“忽视”“中止”或“取消”。不知这是为什么,就是找不到错误!#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
int n=0;
struct student
{
long num;
float score;
struct student *next;
};
int main()
{
struct student *head,*p1,*p2;
head=NULL;
p1=p2=(struct student *)malloc(sizeof(LEN));
printf("Please input num: ");
scanf("%ld",&p1->num);
printf("Please input score: ");
scanf("%f",&p1->score);
while(p1->num!=0)
{
n=n+1;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct student *)malloc(sizeof(struct student));
printf("Please input num: ");
scanf("%ld",&p1->num);
printf("Please input score: ");
scanf("%f",&p1->score);
}
p2->next=NULL;
return 0;
}
#define LEN sizeof(struct student)
p1=p2=(struct student *)malloc(sizeof(LEN));这句就相当于
p1=p2=(struct student *)malloc(sizeof(sizeof(struct student)));也就相当于
p1=p2=(struct student *)malloc(sizeof(4));也就相当于
p1=p2=(struct student *)malloc(4);//因为4是int,所以sizeof(4)就是4 scanf("%f",&p->data.score);///////////问题在这里
这是由于scanf的一个bug造成,
在前面一行加入float pp=0;
使得scanf使用浮点数前先初始化过浮点数就OK.
这是 网上 找的 类似错误 楼主可以参考下哦
RE: 动态创建链表哪儿错了?
本帖最后由 ryxcaixia 于 2015-5-25 16:03 编辑#include<stdio.h>
#include<stdlib.h>
struct student
{
long num;
float score;
struct student *next;
};
// 链表输出函数
void OutputLinklist(student* phead)
{
while (phead->next != NULL)
{
phead = phead->next;
printf("num is %ld\n", phead->num);
printf("scord is %f\n\n", phead->score);
}
}
int main()
{
// 头结点一般为空, 不放任何东西, 头结点的下一结点才会第一个数据结点
student *head = (student *)malloc(sizeof(student));
student* p2 = head;
int n = 0;
scanf("%d", &n);
while(n--)
{
// 申请新结点并赋值
student* p1=(struct student *)malloc(sizeof(struct student));
printf("Please input num: ");
scanf("%ld", &p1->num);
printf("Please input score: ");
scanf("%f", &p1->score);
p1->next = NULL;
// 前驱节点指向后继结点
p2->next = p1;
p2 = p1;
}
OutputLinklist(head);
return 0;
}
楼主同学 我对于逻辑和层次 重写了下 这种表达链表可能更清晰些 #include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct student)
int n=0;
//学生结构体(学生号,成绩)
struct student
{
long num;
float score;
struct student *next;
};
// 链表输出函数
void OutputLinklist(student* phead)
{
while (phead)
{
printf("num is %ld\n", phead->num);
printf("scord is %f\n\n", phead->score);
phead = phead->next;
}
}
int main()
{
struct student *head,*p1,*p2;//*p2是表尾
head=NULL;
p1=p2=(struct student *)malloc(LEN);
//*p1结点输入
printf("Please input num: ");
scanf("%ld",&p1->num);
printf("Please input score: ");
scanf("%f",&p1->score);
while(p1->num)//以num=0作结束标志
{
n=n+1;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
p2=p1;
}
//结点输入
p1=(struct student *)malloc(LEN);
printf("Please input num: ");
scanf("%ld",&p1->num);
printf("Please input score: ");
scanf("%f",&p1->score);
}
p2->next=NULL;
OutputLinklist(head);
free(p1) ;
free(p2) ;
return 0;
} 同意三楼
页:
[1]