c++pointersmemory-managementsyntaxcompiler-errors

Why does int **a = &(&val); result in an error in C++?


I am trying to write a C++ code that gives the address of a pointer, which is itself a pointer. Here’s what I have:

    int val = 10;
    int **a = &(&val);

I got the error

     lvalue required as unary '&' operand
            int **a = &(&val);

I have got the correct output when I used the following code:

    int val = 10;
    int *p = &val;  
    int **a = &p;   

Could someone explain why the first version is incorrect?

I attempted to directly take the address of the address of val using &(&val). I expected this to give me a pointer to a pointer, just as using &p works in the second example.


Solution

  • The first version of your code fails because you try to take the address of the expression &val, which is an rvalue (a temporary value) and does not have a permanent memory address. In C++, you can only take the address of an lvalue (a variable with a persistent memory address).

    In the second version, you store &val in a variable p first, which is an lvalue, and then you can take the address of p, which works correctly.

    So, to fix the issue, you need to use a variable (like p) to hold the address of val before trying to take its address.