[英]C++ pointer to array return type
I have a code like that: 我有这样的代码:
#include <iostream>
using std::cout;
const int ARR_SIZE=5;
int arr[ARR_SIZE];
int (*five(int first))[ARR_SIZE]
{
int result[ARR_SIZE];
for (int i=0;i!=5;++i)
{
result[i]=(i+first);
}
decltype(result) *final_arr=&result;
return final_arr;
}
template <typename T>
void print_arr(T *beg, T *end)
{
cout << "[";
for (;beg!=end;++beg)
cout << *beg << ", ";
cout << "]" << endl;
}
int main()
{
decltype(arr) *a;
for (int i=1;i!=5;++i)
{
a=five(i);
print_arr(std::begin(*a),std::end(*a));
}
return 0;
}
Basically I have a function that returns pointer to array and I would like to print the contents of this array. 基本上我有一个返回数组指针的函数,我想打印该数组的内容。 I would expect this code to print four arrays:
我希望这段代码可以打印四个数组:
[1,2,3,4,5]
[2,3,4,5,6]
[3,4,5,6,7]
[4,5,6,7,8]
However content of the printed arrays seems random. 但是,打印数组的内容似乎是随机的。 I would be greatful for a hint on what is wrong with the code.
我很想知道代码有什么问题。
You are going into undefined behaviour. 您将进入不确定的行为。 You return a dangling pointer in
five
. 您将悬空指针返回
five
。
int result[ARR_SIZE];
life-time is limited by scope of five
, therefore it gets freed at the end. 生命周期受
five
范围的限制,因此最终将其释放。 Taking its address and returning it does not prolong its life. 取回地址并不会延长其寿命。
This decltype(result) *final_arr=&result;
此
decltype(result) *final_arr=&result;
effectively doesn't do anything except hiding the error. 有效地除了隐藏错误之外什么也不做。 You could have skipped it and write
return &result;
您可能会跳过它而写
return &result;
which would most probably upset compiler seriously enough to not compile the code. 这很可能会严重破坏编译器,使其无法编译代码。
您的代码会产生未定义的行为-从five
函数返回悬空指针-这意味着您将返回一个指向对象的指针,该对象已分配在堆栈上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.