结构体操作
函数返回结构体,结构体作为参数传递
在编程中,使用结构体可以很好的保存信息。
将结构体作为返回值
例如信息保存在文件中,我们可以使用文件操作将数据提取出来保存到结构体中,并返回结构体:
函数构造如下:
struct AA{
…
}
struct AA f(){
struct AA a;
…
return a;
}
struct datainfo{
int dev_id;//设备id
char devtype[20];//设备类型
float data;//数据值
float precision;//精度
char units[10];//单位
};
struct datainfo readfile(int n)
{
ifstream outfile;
char buff[100];
int i=0;
datainfo Data;//结构体
//读取文件信息
outfile.open("./datainfo.txt");
//将信息读取到结构体
for(i=0;i<(n-1)*5;i++)
outfile>>buff;
outfile>>Data.dev_id;
cout<<"传感器编号:"<<Data.dev_id<<endl;
outfile>>Data.devtype;
cout<<"传感器名称:"<<Data.devtype<<endl;
outfile>>Data.data;
outfile>>Data.precision;
cout<<"数值:"<<Data.data*Data.precision<<endl;
cout<<"精度:"<<Data.precision<<endl;
outfile>>Data.units;
cout<<"单位:"<<Data.units<<endl;
outfile.close();
return Data;
}
将结构体作为参数传递
在返回结构体后,我们得到了包含数据的结构体,那怎么在其他函数中使用他呢,我们只需要将他作为参数传递给使用的函数就可以使用它内部保存的数据了。
传递有三法:
方法一
传递结构体变量
属于值传递,只是将结构体中的值传递过去,在函数中不能改变结构体的值
struct student
{
int num;
char name[20];
float score[3];
};
定义函数
void change( struct student stu );
函数实现:
void change(struct student stu)
{
stu.score[0] = 100;
strcpy(stu.name, "jerry");
}
mian函数里面调用函数,将结构体变量作为参数传递
int main()
{
struct student stu;
stu.num = 12345;
strcpy(stu.name, "Tom");
stu.score[0] = 67.5;
stu.score[1] = 89;
stu.score[2] = 78.6;
change(stu);
return 0;
}
这里输出结果name依旧为tom,socre[0]依旧为67.5 不能修改结构体的值。
方法二
地址传递
传递结构体的地址作为参数,可以通过地址修改结构体的内容。
函数定义:
void change( struct student* stu );
函数实现:
void change(struct student* p)
{
p->score[0] = 100;
strcpy(p->name, "jerry");
}
main函数调用:
int main()
{
struct student stu;
stu.num = 12345;
strcpy(stu.name, "Tom");
stu.score[0] = 67.5;
stu.score[1] = 89;
stu.score[2] = 78.6;
change(&stu);
return 0;
}
此情况输出的值name为jerry,score[0]=100;
&stu做为实参,是结构体变量stu的地址。在调用时将该结构体地址传给形参p,这样p就指向了stu。
这样在change函数中改变结构体的值,在主函数中输出的值也发生了改变。
方法三
结构体成员的地址传递和值传递
将结构体中的部分成员作为参数传递,不必传递整个结构体,减少时间与空间的开销。