Home > Blockchain >  Declare double pointer from normal variable on single line
Declare double pointer from normal variable on single line

Time:11-18

How can I declare a double pointer and assign its value directly from a normal variable?

int a = 5;
int* b = &a;
int** c = &b;
int** d = &&a;//This does not work
int** e = &(&a);//This does not work

CodePudding user response:

How can I declare a double pointer and assign its value directly from a normal variable

You cannot. "double pointer" is not a special construct in C. It is a short name for a pointer-to-pointer. A pointer always points to a variable, i.e., something with a memory location. &a is an "rvalue", not a variable. It has no memory location and, therefore, you cannot point to it.

CodePudding user response:

The &&a does not work due to the reasons described in the other answer.

However, you can form a desired pointer in a single expression with a help ofcompound literal added in C99. You can view those literals as unnamed local variables. Compund literal are not temporaries but fully legitimate l-values. It is safe to take their address.

int** d = &(int*){&a};
  • Related