简体   繁体   English

如何使用(返回地址)函数打印“*cp”??(请参考我的代码)

[英]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) )??当我使用(返回地址)函数( int*returnsum(int*par,int*pbr) )时是否有任何算法错误??
  2. Is there any logical error when the value("c") moves from returnsum to printresult??当 value("c") 从 returnsum 移动到 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))??当我使用 (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.是的,您正在返回 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??当 value("c") 从 returnsum 移动到 printresult 时是否有任何逻辑错误?

There would not be if the pointer c was valid, but it is not because of the above.如果指针c有效,则不会存在,但这不是因为上述原因。 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.但这并不意味着它是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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