C 找错啦 (运行无错,执行时出错)

来源:百度知道 编辑:UC知道 时间:2024/06/24 11:49:37
#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct student
{
char name[20];
char sex[6];
int num;
int score[3];
float ave; //平均分
struct student * next;
};
struct student * head;
char filename[50];
add() //添加单元
{

struct student *p,*q,*pa=NULL;
int i;
printf("input the number:\n");
scanf("%d",pa->num);
printf("input name:\n");
scanf("%s",pa->name);
printf("input sex:\n");
scanf("%s",pa->sex);
for(i=0;i<3;i++) //循环录入
{
printf("input score[%d]:",i+1);
scanf("%d",&pa->score[i]);
}
if(head==NULL) //头指针为空

head=pa;
p=head;
q=p->next;

主要是分配内存的问题,add函数里没有给pa分配内存
#include "stdafx.h"
#include "iostream.h"
#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct student
{
char name[20];
char sex[6];
int num;
int score[3];
float ave; //平均分
struct student * next;
};
struct student * head;
char filename[50];
add() //添加单元
{

struct student *p,*q,*pa=NULL;
int i;
pa=(struct student *)malloc(sizeof(struct student));
printf("input the number:\n");
scanf("%d",&(pa->num));
printf("input name:\n");
scanf("%s",pa->name);
printf("input sex:\n");
scanf("%s",pa->sex);
for(i=0;i<3;i++) //循环录入
{
printf("input score[%d]:",i+1);
scanf("%d",&pa->score[i]);
}
pa->next=NULL;
if(hea