利用结构体返回多个函数值
#include <iostream.h>
#include <malloc.h>
#include <string.h>
typedef struct student
{
char name[10];
int age;
}Student;
//char tt[5] = {'1','2','3','4','5'};
Student* fun1()
{
Student* ps = new Student;
strcpy(ps->name, "zhong");
//strcpy(ps->name, tt);//直接将数组tt的值赋给数组name,注意不可以用ps->name = tt;//错误,数组之间不能相互赋值
ps->age = 0x100;
return ps;
}
void main()
{
Student* ps=fun1();
cout<<"name:"<<ps->name<<"\t"<<"age:"<<hex<<(*ps).age<<endl;
delete ps;
}
一般的函数只能由一个返回值
如何同时返回 name 和age 呢?
我们可以将其封装到一个结构体中,这样就可以通过结构体的方式同时返回这两个参数
注意:每次使用了fun1后,一定要释放其内部声请的内存空间
比如本程序中的 delete ps; ,否则将造成内存泄漏
浙公网安备 33010602011771号