So here’s what I’m thinking. Let’s say you have the following
So instead of, say,
int v = 5;
int* vptr = &v;
printf(*vptr)
I could do this:
int v = 5:
printf(*&v)
I believe the second code is a pointer to a reference, or vice versa, but is there a way to actually not have to initialize a new variable in order to dereference the memory address? This would help a lot with readability for me personally, plus saving a bit of memory. Thank you.
Pointers are just values. They’re kind-of like integers, that happen to contain values that identify specific pieces of memory. (In fact, at the assembly level, they are exactly that.)
The *&v construct takes the address of the local variable v and then immediately dereferences it, creating a reference to that local variable. This is largely a long way of doing nothing (compared to just saying v) unless v has a more exciting type where you have overridden operator&().
You can create a pointer without a value:
int *vptr = nullptr;
if (vptr) {
printf(*vptr);
}
You can create a value without a pointer:
int v = 5;
printf(v);
You can create a pointer, and initialize it to a value that will live longer than the current functions scope:
int *vptr = new int(5);
if (vptr) {
printf(*vptr);
}
return vptr; // keeps living until you delete it
What, specifically, is it you’re trying to accomplish, though?
Pointer-to-pointer is a thing.
However, anything you point to must have “storage.”
Rvalues don’t have “storage” so you can’t take the address of them. &v returns a rvalue of type pointer, so you can’t directly take the address of that; you have to give it “storage,” which you do by storing it into the heap, or into a variable.
int v1 = 5;
int *pv = &v1;
int **ppv = &pv;
printf(**ppv); // prints 5;
int v2 = 6;
pv = &v2;
printf(**ppv); // prints 6;