C++: Revisiting Pointers

  • 0
Haven't programmed in C++ for a loooooong time... A few concepts got lost in the back of my mind. Here a nice example of pointers for dummies:

#include <iostream>
using namespace std;
 
int main(int argc, char* argv[])
{
    int i = 5;
    int *p = &i;
        int &r = i;
 
    cout << " i =5 ; *p = &i ; &r = i " << endl;
    cout << "Result: " << endl;
    cout << " i =" <<  i << endl;
    cout << "&i =" << &i << endl;
    cout << "*p =" << *p << endl;
    cout << " p =" << p << endl;
    cout << "&p =" << &p << endl;
    cout << " r =" <<  r << endl;
    cout << "&r =" << &r << endl;
 
        cout << "Let's change the value of i: "  << endl;
    i = 6;
    cout << " i =6 ; *p = &i ; &r = i " << endl;
    cout << "Result: " << endl;
    cout << " i =" <<  i << endl;
    cout << "&i =" << &i << endl;
    cout << "*p =" << *p << endl;
    cout << " p =" << p << endl;
    cout << "&p =" << &p << endl;
    cout << " r =" <<  r << endl;
    cout << "&r =" << &r << endl;
 
    return 0;
}

Output:


i =5 ; *p = &i ; &r = i
Result:
 i =5
&i =0x7ffff1c1b12c
*p =5
 p =0x7ffff1c1b12c
&p =0x7ffff1c1b118
 r =5
&r =0x7ffff1c1b12c
Let's change the value of i:
 i =6 ; *p = &i ; &r = i
Result:
 i =6
&i =0x7ffff1c1b12c
*p =6
 p =0x7ffff1c1b12c
&p =0x7ffff1c1b118
 r =6
&r =0x7ffff1c1b12c

No comments:

Post a Comment