Monday, June 2, 2014

Understanding C++ memory and variables


#include <iostream>
using namespace std;
void f1 (int *j)
{
cout << "in f1() beginning-------------\n";
    cout << "       j addr is: " << &j << " is pointed to addr " << j << " value is: " << *j <<"\n";
    int l = 20;
    int *k = &l;
    j = k;
    //k = 0;
    cout << "in f1():======================\n";
    cout << "       l addr is: " << &l << " value is: " << l << "\n";
    cout << "       k addr is: " << &k << " is pointed to addr: " << k << " value is: " << *k << "\n";
    cout << "       j addr is: " << &j << " is pointed to addr " << j << " value is: " << *j <<"\n\n\n";
}

void f2(int **j)
{
    cout << "in f2() beginning-------------\n";
    cout << "       j addr is: " << &j << " is pointed to addr " << j << " value is: " << *j <<"\n";
    cout << "       the value is an address and the exact data is: " << **j << "\n";

    int l = 20;
    int *k = &l;
    *j = k;
    //k = 0;
    cout << "in f2():======================\n";
    cout << "       l addr is: " << &l << " value is: " << l << "\n";
    cout << "       k addr is: " << &k << " is pointed to addr: " << k << " value is: " << *k << "\n";
    cout << "       j addr is: " << &j << " is pointed to addr " << j << " value is: " << *j <<"\n";
    cout << "       the value is an address and the exact data is: " << **j << "\n\n\n";
}

int main()
{
    int i=10;
    int *j = &i;

    cout << "before f1() in main:\n";
    cout << "       j addr is: " << &j << " is pointed to addr " << j << " value is: " << *j << "\n\n";

    f1(j);
    cout << "after f1() in main: \n";
    cout << "       j addr is: " << &j << " is pointed to addr " << j << " value is: " << *j << "\n\n";

    f2(&j);
    cout << "after f2() in main: \n";
    cout << "       j addr is: " << &j << " is pointed to addr " << j << " value is: " << *j << "\n\n";

    return 0;
}
results:
before f1() in main:
      j addr is: 0x28fea8 is pointed to addr 0x28feac value is: 10
in f1() beginning-------------
      j addr is: 0x28fe90 is pointed to addr 0x28feac value is: 10
in f1():======================
      l addr is: 0x28fe7c value is: 20
      k addr is: 0x28fe78 is pointed to addr: 0x28fe7c value is: 20
      j addr is: 0x28fe90 is pointed to addr 0x28fe7c value is: 20
after f1() in main:
      j addr is: 0x28fea8 is pointed to addr 0x28feac value is: 10
in f2() beginning-------------
      j addr is: 0x28fe90 is pointed to addr 0x28fea8 value is: 0x28feac
      the value is an address and the exact data is: 10
in f2():======================
      l addr is: 0x28fe7c value is: 20
      k addr is: 0x28fe78 is pointed to addr: 0x28fe7c value is: 20
      j addr is: 0x28fe90 is pointed to addr 0x28fea8 value is: 0x28fe7c
      the value is an address and the exact data is: 20
after f2() in main:
      j addr is: 0x28fea8 is pointed to addr 0x28fe7c value is: 20