C++ 返回数组指针简单测试:
#include <iostream>
static const size_t ARR_SIZE = 10;
static int arr[ARR_SIZE];
// 更新数组
#define UPDATE_ARR_DATA(i) for (size_t j = 0; j < ARR_SIZE; ++j)\
{\
arr[j] = j * i;\
}\
return &arr;
// 遍历数组
#define iterate_arr(arr_ptr) for (int i = 0; i < ARR_SIZE; ++i)\
{\
std::cout << (*arr_ptr)[i] << std::endl;\
}
/* (*arr_ptr) 这个先解引用数组,返回的是数组指针。 */
// 返回数组指针的函数
static int(*func(int i))[ARR_SIZE]
{
UPDATE_ARR_DATA(i)
}
// typedef 类型别名
typedef int arr_t[ARR_SIZE];
static arr_t* func_t(int i)
{
UPDATE_ARR_DATA(i)
}
// 新标准别名
using arr_alias = int[ARR_SIZE];
static arr_alias* func_alias(int i)
{
UPDATE_ARR_DATA(i)
}
// 尾置返回类型 trailing return type
static auto func_trailing(int i) -> int(*)[ARR_SIZE]
{
UPDATE_ARR_DATA(i)
}
static decltype(arr)* func_decltype(int i)
{
UPDATE_ARR_DATA(i)
}
int main()
{
std::cout << std::endl << "/******原始声明******/" << std::endl << std::endl;
auto v_arr = func(2); // 返回[10]数组的指针
iterate_arr(v_arr)
std::cout << std::endl << "/******typedef 别名******/" << std::endl << std::endl;
auto v_arr_t = func_t(3);
iterate_arr(v_arr_t)
std::cout << std::endl << "/******using 别名******/" << std::endl << std::endl;
auto v_arr_alias = func_t(4);
iterate_arr(v_arr_alias)
std::cout << std::endl << "/******尾置返回类型******/" << std::endl << std::endl;
auto v_arr_trail = func_trailing(5);
iterate_arr(v_arr_trail)
std::cout << std::endl << "/******decltype******/" << std::endl << std::endl;
auto v_arr_decltype = func_decltype(6);
iterate_arr(v_arr_decltype)
return EXIT_SUCCESS;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
输出:
/******原始声明******/
0
2
4
6
8
10
12
14
16
18
/******typedef 别名******/
0
3
6
9
12
15
18
21
24
27
/******using 别名******/
0
4
8
12
16
20
24
28
32
36
/******尾置返回类型******/
0
5
10
15
20
25
30
35
40
45
/******decltype******/
0
6
12
18
24
30
36
42
48
54
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
参考:《C++ Primer》P206