C++ 利用指针和数组以及指针和结构体实现一个函数返回多个值

本文详细介绍并演示了C++中使用指针、数组、结构体及结构体指针返回多个值的四种方法,包括直接返回数组地址、利用结构体打包多个值、使用结构体作为函数返回值以及返回结构体指针。

 

C++ 利用指针和数组实现一个函数返回多个值
demo1

#include <iostream>
using namespace std;
int* test(int,int,int);
int main()
{
int * result =test(1,2,3);
cout<<result[0]<<endl<<result[1]<<endl<<result[2]<<endl;
getchar();
return 0;
}

int * test(int a,int b,int c)
{
int* presult =new int[3];
presult[0] =a;
presult[1] =b;
presult[2] = c;
return presult;
}

输出

1 
2 
3

 


C++ 利用指针和结构体实现一个函数返回多个值
demo2

#include <iostream>
using namespace std;
struct result
{
int first;
double second;
};
result test(int a,double b);
int main()
{
result returnvalue =test(1,2.1234);
cout<<returnvalue.first <<endl<<returnvalue.second<<endl;
getchar();
return 0;
}

result test(int a,double b)
{
struct result ret;
ret.first = a;
ret.second = b;
return ret;
}

输出

1
2.1234

 

 

demo3
c++ 使用结构体作为返回值

#include <stdio.h>
typedef struct {
int a;
int b;
}Stu;
Stu getStu(int x, int y)
{
Stu result;
result.a = x;
result.b = y;
return result;
}
int main()
{
int a = 2, b = 3;
Stu test = getStu(a, b);
printf("%d %d\n", test.a, test.b);
return 0;
}

输出

2 3

 


demo4
c++ 使用结构体指针作为返回值

#include <stdio.h>
#include <stdlib.h>

typedef struct {
int a;
int b;
}Stu;

Stu* getStu(int x, int y)
{
Stu* pStu = (Stu*)malloc(sizeof(Stu));
pStu->a = x;
pStu->b = y;
return pStu;
}

int main()
{
int x = 2, y = 3;
Stu *pStu = getStu(x, y);
printf("%d %d\n", pStu->a, pStu->b);
free(pStu);
return 0;
}

输出

2 3

 

参考:

https://blog.youkuaiyun.com/chaipp0607/article/details/64124704/

https://blog.youkuaiyun.com/dfq12345/article/details/73924580

 

 

转载于:https://www.cnblogs.com/sea-stream/p/11129961.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值