从C++中的函数返回指针
Returning Pointer from a Function in C++
当我从函数返回指针时,它的值可以单独访问。但是,当使用循环输出指针变量的值时,会显示错误的值。我在哪里犯了错误,搞不清楚。
#include <iostream>
#include <conio.h>
int *cal(int *, int*);
using namespace std;
int main()
{
int a[]={5,6,7,8,9};
int b[]={0,3,5,2,1};
int *c;
c=cal(a,b);
//Wrong outpur here
/*for(int i=0;i<5;i++)
{
cout<<*(c+i);
}*/
//Correct output here
cout<<*(c+0);
cout<<*(c+1);
cout<<*(c+2);
cout<<*(c+3);
cout<<*(c+4);
return 0;
}
int *cal(int *d, int *e)
{
int k[5];
for(int j=0;j<5;j++)
{
*(k+j)=*(d+j)-*(e+j);
}
return k;
}
您正在返回一个指向局部变量的指针。
在堆栈上创建CCD_ 1。当cal()
退出时,堆栈被展开,并且该内存是空闲的。事后引用那段记忆会导致未定义的行为(正如这里漂亮地解释的那样:https://stackoverflow.com/a/6445794/78845)。
您的C++编译器应该对此发出警告,并且您应该注意这些警告。
值得一提的是,以下是我如何在C++中实现这一点:
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
int main()
{
int a[] = {5, 6, 7, 8, 9};
int b[] = {0, 3, 5, 2, 1};
int c[5];
std::transform (a, a + 5, b, c, std::minus<int>());
std::copy(c, c + 5, std::ostream_iterator<int>(std::cout, ", "));
}
看它跑!
int k[5]
数组在堆栈上创建。因此,当它从cal
返回超出范围时,它会被销毁。您可以使用第三个参数作为输出数组:
void cal(int *d, int *e, int* k)
{
for(int j=0;j<5;j++)
{
*(k+j)=*(d+j)-*(e+j);
}
}
像这样调用cal
:
int a[]={5,6,7,8,9};
int b[]={0,3,5,2,1};
int c[5];
cal (a, b, c); // after returning from cal, c will be populated with desired values
正如其他人所指出的,您将返回一个指向本地变量,这是未定义的行为。然而,真正的问题是您需要返回一个数组,而C样式的数组已损坏。用std::vector<int>
替换数组,忘记指针(因为您处理的是值),代码就会起作用。
相关文章:
- 在函数中返回无符号字符数组,但不返回指针
- 为什么需要返回指针来利用协方差?
- 野牛如何在解析树中返回指针
- 何时返回指针与返回对象的一般经验法则?
- 为什么使用 std::istream_iterator 构造函数返回指针
- 为什么我不能直接从返回指针的函数返回对指针的引用?
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 为什么下面的代码段返回指针指向的值而不是指针的地址?
- 使用 map<char,strring> 的迭代器返回指针 map<char,strring>*
- 如何从类成员函数返回指针,例如 size_t * class :: function(); 并使用类析构函数 ~size
- 函数返回动态强制转换的指针,返回指针,就好像它根本没有被转换一样
- 从函数返回对指针的引用与返回指针相同?
- C++ 为什么访问数组中的元素会返回指针?
- 关于函数返回指针
- 返回指针或对私有成员的引用的替代方法
- 从函数返回指针
- 通过从当地的C风格阵列中返回指针来获取一个悬空的指针
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 为什么C 模板功能不支持返回指针
- 返回指针的语句 - 解释它是如何工作的以及为什么