Why am I unable to get the address of an int* function?

I wrote a program to explore pointers, the dereferencing operator, and the address of operator. I noticed that p, x, and varMim() have addresses but the program returned an error when I tried to output &ptrMim(xvar):

In function 'void printMimicTable(int&, int*&)':
Line 38 error: lvalue required as unary '&' operand

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// PBachmann
// & and * Operator Toy

#include <iostream>
#include <iomanip>

using namespace std;

int x = 1829, *p = &x;

// This function mimics the behavior of a pointer
int *ptrMim(int &var){ return (&var); }
// This function mimics the behavior of a variable
int &varMim(){ return x; }

// Prints a table comparing x and p using "passing by value" method
void printValueTable(int xvar, int* pvar){
    cout << "  Name | Contents | Address  | Deref\n";
    cout << "-------+----------+----------+-------\n";
    cout << setw(8) << "x |" << setw(9) << xvar << " |" << setw(9) << &xvar << " |   -" << endl;
    cout << setw(8) << "p |" << setw(9) << pvar << " |" << setw(9) << &pvar << " |" << setw(6) << *pvar << endl;
    cout << endl;
}

// Prints a table comparing x and p using "passing by reference" method
void printReferenceTable(int &xvar, int* &pvar){
    cout << "  Name | Contents | Address  | Deref\n";
    cout << "-------+----------+----------+-------\n";
    cout << setw(8) << "x |" << setw(9) << xvar << " |" << setw(9) << &xvar << " |   -" << endl;
    cout << setw(8) << "p |" << setw(9) << pvar << " |" << setw(9) << &pvar << " |" << setw(6) << *pvar << endl;
    cout << endl;
}

// Prints a table comparing p to ptrMim() and x to varMim()
void printMimicTable(int &xvar, int* &pvar){
    cout << "  Name | Contents | Address  | Deref\n";
    cout << "-------+----------+----------+-------\n";
    //cout << setw(8) << "ptrMim |" << setw(9) << ptrMim(xvar) << " |" << setw(9) << &ptrMim(xvar) << " |" << setw(6) << *ptrMim(xvar) << endl;
    cout << setw(8) << "ptrMim |" << setw(9) << ptrMim(xvar) << " |    -     |" << setw(6) << *ptrMim(xvar) << endl;
    cout << setw(8) << "p |" << setw(9) << pvar << " |" << setw(9) << &pvar << " |" << setw(6) << *pvar  << endl;
    cout << setw(8) << "varMim |" << setw(7) << varMim() << "   |" << setw(9) << &varMim() << " |   -" << endl;
    cout << setw(8) << "x |" << setw(7) << xvar << "   |" << setw(9) << &xvar << " |   -" << endl;
    cout << endl;
}

int main(){

    printValueTable(x, p);
    printReferenceTable(x, p);
    printMimicTable(x, p);

    return 0;
}


Why am I unable to get the address of an int* function?
Last edited on
There is no such thing as an int* function.
You have a function that returns an int*.

The returned value is not a variable, but a temporary, so you can't get its address.
Topic archived. No new replies allowed.