I am fairly new to C++. I was going through tutorialspoint course on the same. While using its inbuilt compiler (GNU GCC v7.1.1) to learn about pointers, I found a rather unusual behaviour (stated in observation section below) that I just cannot comprehend.
I performed following scenarios trying to reach some concrete inference-
Scenario 1
Code -
int main () {
int *ptr;
cout << "The value of ptr is " << ptr;
return 0;
}
Output -
The value of ptr is 0
Scenario 2
Code -
int main () {
int a =20;
int *ptr;
cout << "The value of ptr is " << ptr;
return 0;
}
Output -
The value of ptr is 0x7ffff0278150
Scenario 3
Code -
int main () {
int a =20;
int *ptr;
cout<<"The address of a is "<<&a<<"\n";
cout << "The value of ptr is " << ptr;
return 0;
}
Output -
The address of a is 0x7ffcee0e2e74
The value of ptr is 0
Observation
Scenario 1: By default, either pointer is pointing to NULL or OS has cleaned out existing data from the memory location assigned to ptr. Anyhow, I don't find this output unexplainable.
Scenario 2: This is weird scenario. Just assigning value to some new variable causes my pointer to store some garbage memory address. Just to note, I haven't explicitly assigned my pointer to point to that variable or any other variable for that matter.
Scenario 3: Independently, this scenario is simplest to understand. But when taken into consideration along with 2nd, it complexes 2nd even more.
Can anyone please explain or hypothesise on what could possibly be happening around here ??