C++之函数返回指针类型
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <malloc.h>
using namespace std;
template<class T>
int get_array_length(T &arr);
int *get_random();
int main() {
system("chcp 65001");
int *p;
p = get_random();
int size = 10;
for (int i = 0; i < size; ++i) {
cout << *p << endl;
p++;
}
return 0;
}
template<class U>
int get_array_length(U &arr) {
return sizeof(arr) / sizeof(arr[0]);
}
int *get_random() {
static int r[10];
int size = 0;
size = get_array_length(r);
srand((unsigned(time(nullptr))));
for (int i = 0; i < size; ++i) {
r[i] = rand();
cout << "数组中的每个元素:" << r[i] << endl;
}
return r;
}
输出:
Active code page: 65001
数组中的每个元素:14718
数组中的每个元素:27617
数组中的每个元素:4497
数组中的每个元素:22310
数组中的每个元素:23275
数组中的每个元素:10427
数组中的每个元素:28641
数组中的每个元素:5342
数组中的每个元素:20998
数组中的每个元素:992
14718
27617
4497
22310
23275
10427
28641
5342
20998
992
C++ 不支持在函数外返回局部变量的地址,除非定义局部变量为 static变量。所以想要在get_random()外部获取到局部变量r数组的地址,需要用static来修饰。我们这里返回的对象其实还是之前博客写到的返回的数组,也就是指针常量。