int main() {
int x=10;
int *p=&x;
int &y =*p;
cout<< x << endl << &x <<endl;
cout<< *p << endl << p <<endl;
cout<< y << endl << &y <<endl;
p++;
*p = 20;
cout<< x << endl << &x <<endl;
cout<< *p << endl << p <<endl;
cout<< y <<endl<< &y <<endl;
return 0;
}
Above is the code which would best explain my question. Normally, a variable reference (&) takes the address of a variable and starts referring to the same. I have tried doing the same through a pointer. I have defined a variable, pointer p points to x and a reference variable y refers to *p. Would this mean that y refers to the same variable x now? As the next step, I stopped pointing to x through *p, what happens to reference variable y now? What would it hold. In the code above, cout<
Can someone help explain the behavior here.
If we need to modify a pointer rather than the object that the pointer is pointing to, we pass a pointer by reference.
Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.
Passing Reference to a Pointer in C++ Note: It is allowed to use “pointer to pointer” in both C and C++, but we can use “Reference to pointer” only in C++. If a pointer is passed to a function as a parameter and tried to be modified then the changes made to the pointer does not reflects back outside that function.
Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to. References: A reference variable is an alias, that is, another name for an already existing variable.
[note: this answer is only about C++. In C, your code shouldn't compile.]
Yes, after you initialize y
, it refers to x
. Incrementing p
doesn't change that -- y
still refers to x
.
Unfortunately, when you do the p++; *p=20;
, you've modified p
so it no longer refers to any allocated storage. When you write to it, you get undefined behavior. That means it's perfectly reasonable for the program to halt (or do essentially anything else).
Note, however, that incrementing p
is entirely allowable--in this respect, x
acts like an array of one element, and forming a pointer to one past the last element of an array is explicitly allowed. It's only when you write to the address that pointer refers to that you get the undefined behavior. (That is: p++;
is fine; *p=20;
is not).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With