3

I don't understand why I can't print the address of the pointer. I know it's pretty fundamental to understand pointers, so any help is appreciated.

void printp(int& test)
{
        cout << test << endl;
}

int main()
{
        int *p = new int;
        *p = 1;
        int np = 0;

//      printp(p);  // why doesn't this print the address of p?
//      printp(&p); // why doesn't this print the address of p?
        printp(*p); // prints 1
        printp(np); // prints 0

return 0;
}

I get the below error when I try using 'printp(p)'.

test.cpp: In function ‘int main()’:
test.cpp:17:10: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
  printp(p);  // why doesn't this print the address of p?
          ^
test.cpp:5:6: note:   initializing argument 1 of ‘void printp(int&)’
 void printp(int& test)
      ^~~~~~
test.cpp:17:10: error: cannot bind rvalue ‘(int)p’ to ‘int&’
  printp(p);  // why doesn't this print the address of p?

4 Answers4

8

You get the error message from the compiler because the compiler requires exact types for reference parameters.

When a function has a reference parameter

void printp(int& test);

instead of a pointer parameter,

void printp(int* test);

the caller must provide a variable of the exact type. It can't provide a reference to a variable of any other type (except for when you can dynamic_cast from the other type to the parameter's type).

So when you call printp(p);, the compiler requires that p be of type int, not int *.

If you pass by value, the compiler will promote or static_cast some types for you,

void printp(int test);
short s = 0;
printp( s ); // s is promoted to int here.

but the compiler can't do that for you when the parameter is a reference.

RichS
  • 540
  • 1
  • 6
  • 12
2

In your code printp(int&) is a function that takes a reference not a pointer so to get the address of pointer in your case you can simply change it or overload it:

void printp(int* test){
    cout << test << endl; // the addres test contains not its address
    cout << &test << endl; // the address of test itself
    cout << *test << endl; // the value in the address that test points to
}

In main:

printp(p);

The output:

00893250
0018FEEC
1
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
2

For int a;:

expr | type
-----+-----
&a   | int*
a    | int
*a   | - (not valid)

for int* p;:

expr   | type
-------+-----
&p   | int**
p    | int*
*p   | int
**p  | - (not valid)

for int** pp;

expr   | type
-------+-----
&pp   | int***
pp    | int**
*pp   | int*
**pp  | int
***pp | - (not valid)
bolov
  • 72,283
  • 15
  • 145
  • 224
0

int& is a reference to int not a pointer. You need to change the function definition to:

void printp(int* test)
{
   cout << test << endl;
}

then in the main()

printp(p);
printp(&np);

this will output something like:

0x55847f523c20
0x7ffffc7fb07c
grygoriim
  • 51
  • 2