简体   繁体   中英

Return address of pointer through function

#include<iostream>

using namespace std;

int teradata=65;

int &pointer(int *p2)
{
       p2=&teradata;
       return &p2;
}

int main()
{
       int a=10;
       int *p=&a;
       int **p3;
       p3=pointer(p);
       cout<<p3;    
       return 0;
}

Actually I am trying to return the address of pointer p2 and store it in pointer p3 which is a pointer to a double. Please help correct this program and tell me the error which I did in this program.

The operation &p2 returns the address of p2 . p2 is a pointer to int . So the function pointer should return int ** and not int & :

int **pointer(int *p2) {
       p2=&teradata;
       return &p2;
}

Since a function parameter is basically an initialized local variable, returning its address is unproductive if the variable is an object. The object no longer exists when the function returns, so the address itself is also invalid.

If you actually want the address of the pointer variable that was passed to the function, the function needs to accept a reference to the pointer variable being passed. And, it needs to specify the correct return type, which is a pointer to a pointer.

int **pointer(int *&p2) {
       p2=&teradata;
       return &p2;
}

Your code should not have compiled, and your compiler should have issued a diagnostic about an invalid conversion.

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