C 文件简单小麻烦

来源:百度知道 编辑:UC知道 时间:2024/06/19 15:35:07
#include<stdio.h>
#include<stdlib.h>
typedef struct student{
char name[6];
char sex;
int age;
struct student *next;
}STU;

void write();
void read();

void main()
{
write();
//read();
}
void write()
{
FILE *fp;
STU *head,*p,*ptr,*q;
char ch;
head=(STU*)malloc(sizeof(STU));
head->next=NULL;
ptr=head;

do{
p=(STU*)malloc(sizeof(STU)); //输入信息
scanf("%s %c %d",&p->name,&p->sex,&p->age);
p->next=ptr->next;
ptr->next=p;
ptr=p;
ch=getchar();
}while(ch!='#');
p=head->next;
while(p)
{
printf("%s %c %d\n",p->name,p->sex,p->age);
p=p->next;
}

if((fp=fopen("air.txt","w+"))==NULL)
{
printf("can not open this file!!!\n"

没分配空间是不对滴~~
C语言中有句话要记着,错误的代码不一定给出错误的结果。
如:
char a[3];
a[0]='1';a[1]='2';a[2]='3';a[3]='4';a[4]='5';a[5]='\0';
printf("%s",a);
显然这是错误的,但是你也能得到正确的结果。虽然程序没有为 a[3]--a[5]分配空间。但是这段空间是随时会被别的数据覆盖的。危险呐!
细节吧不把握,小程序看不出来,以后大程序你就有的苦头吃了。