地址交换问题
////////////////////////////////////////
//下面一个程序,运行时有错误, //
//我却不是很明白是怎么回事,请各位帮忙看看……//
//(不知道是不是交换地址的时候错了) //
////////////////////////////////////////
#include<iostream.h>
//完成一项录入按回车键切入下一项
//分数以空格间开
class student
{
public:
int number;
char name[30],sex[10];
int Englishgrade,Mathgrade,Physicsgrade;
}stu1[10];
void main()
{
int a,b,c,i;
student *t,*x,*y;
cout<<"please set 5 student' data.\n";
for(i=1;i<=5;i++)
{
cout<<"\n set the number of:"<<i<<"\n";
cin>>stu1[i].number;
cout<<"\n set the name of:"<<i<<"\n";
cin>>stu1[i].name;
cout<<"\n set the sex :"<<i<<"\n";
cin>>stu1[i].sex;
cout<<"\n set the grade of English,Math,Physics of :"<<i<<"\n";
cin>>stu1[i].Englishgrade>>stu1[i].Mathgrade>>stu1[i].Physicsgrade;
}
for(a=1;a<=5-1;a++)
for(b=1;b<=5-a;b++)
if(stu1[b].number>stu1[b+1].number)
{x=&stu1[b];
y=&stu1[b+1];
t=x;
x=y;
y=t;
&stu1[b]=x;
&stu1[b+1]=y;
}
for(c=1;c<=5;c++)
cout<<"\n"<<stu1[c].number<<"\t"<<stu1[c].name
<<"\t"<<stu1[c].sex<<"\t"<<stu1[c].Englishgrade<<"\t"
<<stu1[c].Mathgrade<<"\t"<<stu1[c].Physicsgrade<<"\n";
}
[解决办法]
运行时出的错??编译通过了?
#include <iostream.h> #include <memory.h>//完成一项录入按回车键切入下一项 //分数以空格间开 class student { public: int number; char name[30],sex[10]; int Englishgrade,Mathgrade,Physicsgrade; }stu1[10]; void main() { int a,b,c,i; student t; //这里改了 cout <<"please set 5 student' data.\n"; for(i=1;i <=5;i++) { cout <<"\n set the number of:" <<i <<"\n"; cin>>stu1[i].number; cout <<"\n set the name of:" <<i <<"\n"; cin>>stu1[i].name; cout <<"\n set the sex :" <<i <<"\n"; cin>>stu1[i].sex; cout <<"\n set the grade of English,Math,Physics of :" <<i <<"\n"; cin>>stu1[i].Englishgrade>>stu1[i].Mathgrade>>stu1[i].Physicsgrade; } for(a=1;a <=5-1;a++) for(b=1;b <=5-a;b++) if(stu1[b].number>stu1[b+1].number) { /* x=&stu1[b]; y=&stu1[b+1]; t=x; x=y; y=t; &stu1[b]=x; //《-----什么NB编译器啊?这也能编译通过?! &stu1[b+1]=y; //交换的是里面的数据,不是地址 */ memcpy(&t, stu1+b, sizeof(student)); memcpy(stu1+b, stu1+b+1, sizeof(student)); memcpy(stu1+b+1, &t, sizeof(student)); } for(c=1;c <=5;c++) cout <<"\n" <<stu1[c].number <<"\t" <<stu1[c].name <<"\t" <<stu1[c].sex <<"\t" <<stu1[c].Englishgrade <<"\t" <<stu1[c].Mathgrade <<"\t" <<stu1[c].Physicsgrade <<"\n"; }