cpp:函数返回数组
一、函数返回数组
1 #include<iostream>
2
3
4 using namespace std;
5
6
7 int* ret_array()
8 {
9 int a[]={1,2,3,4,5,6};
10 int *pt=a;
11 return pt;
12 }
13
14
15 void print_array(int size, int* (*pt)())
16 {
17 for(int i=0; i<size; i++)
18 {
19 // 调用返回值为数组的函数
20 cout << "array["<< i <<"]="<< pt()[i]<< endl;
21 }
22 }
二、代码运行
1 [root@rockylinux tmp]# uname -a
2 Linux rockylinux 4.18.0-372.19.1.el8_6.x86_64 #1 SMP Tue Aug 2 16:19:42 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
3 [root@rockylinux tmp]#
4 [root@rockylinux tmp]# g++ --version
5 g++ (GCC) 8.5.0 20210514 (Red Hat 8.5.0-10)
6 Copyright (C) 2018 Free Software Foundation, Inc.
7 This is free software; see the source for copying conditions. There is NO
8 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9
10 [root@rockylinux tmp]#
11 [root@rockylinux tmp]# cat return_array.cpp
12 #include<iostream>
13
14
15 using namespace std;
16
17
18 int* ret_array()
19 {
20 int a[]={1,2,3,4,5,6};
21 int *pt=a;
22 return pt;
23 }
24
25
26 void print_array(int size, int* (*pt)())
27 {
28 for(int i=0; i<size; i++)
29 {
30 // 调用返回值为数组的函数
31 cout << "array["<< i <<"]="<< pt()[i]<< endl;
32 }
33 }
34
35
36 int main(int argc, char* argv[], char* envp[])
37 {
38 print_array(6,ret_array);
39
40 return 0;
41 }
42 [root@rockylinux tmp]#
43 [root@rockylinux tmp]# g++ -g -o return_array return_array.cpp
44 [root@rockylinux tmp]#
45 [root@rockylinux tmp]# ./return_array
46 array[0]=1
47 array[1]=2
48 array[2]=3
49 array[3]=4
50 array[4]=5
51 array[5]=6
52 [root@rockylinux tmp]#
53 [root@rockylinux tmp]#
本文由 lnlidawei 原创、整理、转载,本文来自于【博客园】; 整理和转载的文章的版权归属于【原创作者】; 转载或引用时请【保留文章的来源信息】:https://www.cnblogs.com/lnlidawei/p/16670253.html