简体   繁体   中英

How can I print " *cp " using (Return address )function??( please refer my code)

  1. Is there any Algorithms error when I use (Return address)function( int*returnsum(int*par,int*pbr) )??
  2. Is there any logical error when the value("c") moves from returnsum to printresult?? ( there is no error when I execute the program!! )

#include<iostream>
using namespace std;

int* returnsum(int* par, int* pbr);
void printresult(int* cp);

int main()
{
    int a;
    int b;
    int* pa = &a;
    int* pb = &b;
    int* c;
    cout << "Enter two numbers:";
    cin >> a >> b;
    c=returnsum(pa, pb);
    printresult(c);
    return 0;
}

int* returnsum(int*par,int*pbr)
{
    int sum=0;
    sum = *par + *pbr;
    
    return &sum;
}
void printresult(int *cp)
{
    cout << *cp;
}

Is there any Algorithms error when I use (Return address)function(int returnsum(int par,int*pbr))??

Yes, you are returning the address of a local variable that has gone out of scope. This is a dangling pointer and it is Undefined Behaviour to dereference it.

Is there any logical error when the value("c") moves from returnsum to printresult??

There would not be if the pointer c was valid, but it is not because of the above. Do yourself a favour here and forget about pointers, just return by value. You do not gain anything by returning a pointer in this case.

( there is no error when I execute the program!! )

In cases of undefined behaviour the program may appear to work correctly. But this does not mean that it is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM