在 C++ 中从函数返回指针 [英] Returning Pointer from a Function in C++

查看:42
本文介绍了在 C++ 中从函数返回指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I return pointer from the function, its value can be accessed individually. But when a loop is used to ouput the value of that pointer variable, wrong value is shown. Where I am making mistake, can't figure it out.

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

推荐答案

int k[5] 数组是在栈上创建的.因此,当它通过从 cal 返回而超出范围时,它会被销毁.您可以使用第三个参数作为输出数组:

The int k[5] array is created on the stack. So it gets destroyed when it goes out of scope by returning from cal. You could use a third parameter as an output array:

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++ 中从函数返回指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆