c++的一个小程序的问题

来源:百度知道 编辑:UC知道 时间:2024/09/21 05:41:30
本人初学c++,用的是dev-c,版本是4.9.8.0.。
以下是我写的一个程序,先定义一个student结构然后让用户输入人数和每个student的名字和分数,这个程序已经成功编译完了,可奇怪的是,一到输入第一个student的name成员时就出错,肯定是在while循环里除了问题,请问各位高人为什么??由于是新人所以没分,谢谢您的帮助!

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
struct Student{char name[20];float score;};
int main(int nNumberofArgs, char* pszArgs[])
{
Student* students;
int studentnum;
cout<<"please input student number"<<endl;
cin>> studentnum;
students= new Student[studentnum];
if(students=NULL)
{
cout<<"Error1\n";
return 0;
}
int i=0;
while ( i<studentnum)
{
cout<<"please input the "<<i+1<<"-te student's name \n";
cin >>students[i].name;
cout<<"please input the "<<i+1<<"-te student's score\n";

第十二行:if(students=NULL)//这里出错了.
{
cout<<"Error1\n";
return 0;
}

结果是students为空,所以在给students赋值时会出错.
而students=NULL相当于NULL,
if(NULL)//也就会跳过下面的代码.不会输出出错信息
{
cout<<"Error1\n";
return 0;
}

用Student* students访问动态分配的数组,因为动态分配的数组在内存中是不连续的,不能用下标访问,用他的接受指针进行操作.

问题出在你后面计算总和的循环上
for(int i=0;i<studentnum;i++)
{
sum+=students[i++].score; //怎么还来个i++?!?!
}
改为
for(int i=0;i<studentnum;i++)
{
sum+=students[i].score;
}
就OK了.