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

标签 c++ arrays pointers

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

#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;
}

最佳答案

您正在返回一个指向局部变量的指针。

k 是在堆栈上创建的。当 cal() 退出时,堆栈被展开并且内存被释放。之后引用该内存会导致未定义的行为(如此处精美解释:https://stackoverflow.com/a/6445794/78845)。

您的 C++ 编译器应该对此发出警告,您应该注意这些警告。

对于它的值(value),这里是我如何在 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, ", "));
}

See it run!

关于c++ - 从 C++ 中的函数返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8969292/

相关文章:

c++ - 数组 C++ 中每个 boolean 值 1 位

c++ - 指针和整数 C++ 之间的比较问题

关于指针和多维数组的困惑

javascript - 在javascript中将对象展平为数组

c++ - 在析构函数中多次删除

c - 如何在不触发警告的情况下将整数值转换为指针地址

c++ - VC++ 6.0 从 COM DLL 生成的 .TLH 结果出错

c++ - 如何检查一个数字被输入了多少次

c++ - 使用带有 lambda 谓词的 std::remove_if 删除多个元素

Java 将方法字符串拆分为方法名称和参数