从C++中的函数返回指针

Returning Pointer from a Function in C++

本文关键字:返回 指针 函数 C++      更新时间:2023-10-16

当我从函数返回指针时,它的值可以单独访问。但是,当使用循环输出指针变量的值时,会显示错误的值。我在哪里犯了错误,搞不清楚。

#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>替换数组,忘记指针(因为您处理的是值),代码就会起作用。