-4
#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.

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
  • Please [get a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read, and learn the difference between *pointer* and *references*. – Some programmer dude Feb 05 '19 at 08:37
  • When you say, "correct this program", what is wrong according to you? What did you expect and what you got? – Jay Feb 05 '19 at 08:38
  • 1
    `pointer to a double`...say what? – Sourav Ghosh Feb 05 '19 at 08:39
  • You could return `int**` as the answers suggest. Just don't forget that the return value will be useless as the address stored at the first level of indirection was temporary (local to the `pointer(int *p2)` function). – George Feb 05 '19 at 08:49

2 Answers2

1

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;
}
john
  • 85,011
  • 4
  • 57
  • 81
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
1

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.

jxh
  • 69,070
  • 8
  • 110
  • 193