链表问题
程序代码:#include "stdio.h"
#include "stdlib.h" /*包含动态内存分配函数的头文件*/
#define N 1
#define LEN sizeof(struct student)
struct student
{
char num[6];
char name[8];
char sex;
int score;
struct student *next;
};
int i;
struct student *input()
{
struct student *head,*p1,*p2; //定义指向struct student的指针,head为头指针,p1为当前结点,p2为当前结点的前一个结点
p1=p2=(struct student *)malloc(LEN); //开辟LEN大小的内存空间,并且将返回的值(开辟的地址)强制类型转换为struct student*,然后再赋给p1,p2;
head=NULL; //令头指针head=NULL
for(i=0;i<N;i++)
{
if(i==0) head=p1; //如果开辟的结点是第一个,就把指针p1的值(开辟的地址)赋给head.(整个循环中只使用此语句一次)
else (p2->next)=p1; //否则 把指针p1的值(开辟的地址)赋给当前结点的前一个结点的next
p2=p1; //把指针p1的值(开辟的地址)赋给p2
p1=(struct student *)malloc(LEN); //重新再开辟LEN大小的内存空间,并且将返回的值(开辟的地址)强制类型转换为struct student*,赋给p1
printf("输入学号\n"); //输入当前结点的数据
scanf("%s",&p1->num);
printf("输入姓名\n");
scanf("%s",&p1->name);
printf("输入性别\n");
scanf("%s",&p1->sex);
printf("输入分数\n");
scanf("%d",&p1->score);
printf("\n");
}
p2->next=NULL; //最后一个结点的next=NLL
return(head); //返回头指针
}
int main()
{
struct student *pt;
pt = input();
printf("%5.1s,%5.1s,%5.1s,%5.1d",pt->num,pt->name,pt->sex,pt->score);
}想输出第一个节点的数据,编译运行都通过,可是老错







大家瞅瞅啊


