When I tried to access the value(which is an address) stored in the address pointed by the pointer variable, a garbage value is returned. I have posted the code and the output below.
Code:
#include<iostream>
using namespace std;
int main(){
int *a, b=10, *c;
a = &b;
c = &b+1;
cout << "Address of A : " << &a << endl;
cout << "Value of A : " << a << endl;
cout << "Value pointed by A : " << *a << endl;
cout << "Address of B : " << &b << endl;
cout << "Value of B : " << b << endl;
cout << "Value of C : " << c << endl;
cout << "Value pointed by C : " << *c << endl;
return 0;
}
Output:
Address of A : 0x7fff3e608d20
Value of A : 0x7fff3e608d1c
Value pointed by A : 10
Address of B : 0x7fff3e608d1c
Value of B : 10
Value of C : 0x7fff3e608d20
Value pointed by C : 1046514972
In the above program, the address pointed by c
is the address of a
yet *c
gives garbage value 1046514972
instead of 0x7fff3e608d1c
.
I know, I can access the value of A in some other way but my question is why couldn't I access it in this way. Is this an expected behaviour? If yes, can somebody please explain? Thank you.