Search code examples
c++pointersassignment-operatordereference

Strange output when use Pointers in c++


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):

  1. 0x7fff568e52e0
  2. 0x7fff568e52e8
  3. 2
  4. 2
  5. 0x7fff568e52e0
  6. '-----------'
  7. 0x7fff568e52e4
  8. 0x7fff568e52e8
  9. 0
  10. 8
  11. 0x7fff568e52e4

Except for 7 and 9, all outputs were expected for me. I appreciate someone explaining them to me.


Solution

  • 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.

    1. 0x7fff568e52e4

    and this call

    std::cout << *p << std::endl;
    

    outputs the indeterminate value of y that happily is equal to 0.

    9. 0