Considere the following code in c :
#include <iostream>
using namespace std;
int main() {
int x=2, y;
int *p = &x;
int **q = &p;
std::cout << p << std::endl;
std::cout << q << std::endl;
std::cout << *p << std::endl;
std::cout << x << std::endl;
std::cout << *q << std::endl;
*p = 8;
*q = &y;
std::cout << "--------------" << std::endl;
std::cout << p << std::endl;
std::cout << q << std::endl;
std::cout << *p << std::endl;
std::cout << x << std::endl;
std::cout << *q << std::endl;
return 0;
}
The output of code is (of course the list numbers is not the part of output):
- 0x7fff568e52e0
- 0x7fff568e52e8
- 2
- 2
- 0x7fff568e52e0
- '-----------'
- 0x7fff568e52e4
- 0x7fff568e52e8
- 0
- 8
- 0x7fff568e52e4
Except for 7 and 9, all outputs were expected for me. I appreciate someone explaining them to me.
CodePudding user response:
The variable y
was not initialized
int x=2, y;
So it has an indeterminate value.
As the pointer q
points to the pointer p
int **q = &p;
then dereferencing the pointer q
you get a reference to the pointer p
.
So this assignment statement
*q = &y;
in fact is equivalent to
p = &y;
That is after the assignment the pointer p
contains the address of the variable y
.
So this call
std::cout << p << std::endl;
now outputs the address of the variable y
.
- 0x7fff568e52e4
and this call
std::cout << *p << std::endl;
outputs the indeterminate value of y
that happily is equal to 0.
9. 0