注册 登录
编程论坛 C++教室

麻烦看下这个程序

aiyinsitan 发布于 2011-04-02 13:21, 517 次点击
#include <iostream.h>
#include <string.h>
#include <malloc.h>
#define LEN sizeof(struct student)//student 这个结构的长度
struct student  //定义结构
{
    long num;
    char name[20];
    float score[30];
};
void input(struct student *p);//输入函数
void print(struct student *p);//输出函数
void main()
{
    int i;
    struct student *p[5];//定义一个指针数组
    for(i=0;i<1;i++)
    {
      input(p[i]);
    }
    for(i=0;i<1;i++)
    {
    print(p[i]);
    }
}
void input(struct student *p)
{
    int j;
  p=(struct student *)malloc(LEN);
         cin>>p->num;
     cin>>p->name;
     for(j=0;j<3;j++)
     {
         cin>>p->score[j];
     }
}
void print(struct student *p)
{
     int i;
     //struct student *p1;
     //p=(struct student *)malloc(LEN);
     //p1=p;
     cout<<p->num<<"  ";
     cout<<p->name<<"  ";
     for(i=0;i<3;i++)
     {
         cout<<p->score[i];
     }
     cout<<endl;
}
总共有5个学生,三门成绩,用input函数输入,用print函数输出 输入没问题  但输出的时候  提示内存提示错误
3 回复
#2
aiyinsitan2011-04-02 13:57
#include <iostream.h>
#include <string.h>
#include <malloc.h>
#define LEN sizeof(struct student)//student 这个结构的长度
struct student  //定义结构
{
    long num;
    char name[20];
    float score[30];
};
void input(struct student *p);//输入函数
void print(struct student *p);//输出函数
void main()
{
    int i;
    struct student *p[5];//定义一个指针数组
    for(i=0;i<5;i++)
    {
     p[i]=(struct student *)malloc(LEN);
      input(p[i]);
    //print(p[i]);
    }
    for(i=0;i<5;i++)
    {
    print(p[i]);
    }
}
void input(struct student *p)
{
    int j;
  
         cin>>p->num;
     cin>>p->name;
     for(j=0;j<3;j++)
     {
         cin>>p->score[j];
     }
}
void print(struct student *p)
{
     int i;
     //struct student *p1;
     //p=(struct student *)malloc(LEN);
     //p1=p;
     cout<<p->num<<"  ";
     cout<<p->name<<"  ";
     for(i=0;i<3;i++)
     {
         cout<<p->score[i];
     }
     cout<<endl;
}
#3
hellovfp2011-04-02 14:19
第二个输出正常,你想说什么呢?忘了分配内存就开始接收数据?
#4
aiyinsitan2011-04-03 16:30
回复 3楼 hellovfp
恩了  SB 了
1