Friday, January 25, 2013

Understand pointer to a pointer (**)

// program illustrating the pointer to pointer (**)
#include <iostream>
using namespace std;

int main()
{
    int i = 3;
    int *j;
    int **k;
   
    j = &i;
    k = &j;
   
    cout << "\n Address of i: " << &i << endl;
    cout << "\n Address of i: " << j << endl;
    cout << "\n Address of i: " << *k << endl;
    cout << "\n Address of j: " << &j << endl;
    cout << "\n Address of j: " << k << endl;
    cout << "\n Address of k: " << &k << endl;
   
    cout << "\n value of i: " << j << endl;
    cout << "\n value of k: " << k << endl;
    cout << "\n value of i: " << i << endl;
    cout << "\n value of i: " << *(&i) << endl;
    cout << "\n value of i: " << *j << endl;
    cout << "\n value of i: " << **k << endl;
    return 0;
}

OUTPUT:
Pointer terminology:
    int a = 12;
    int *b;
    b = &a;
   
    1. b contains address of an int
    2. value at address contained in b is an int
    3. b is an int pointer
    4. b points to an int
    5. b is a pointer which points in the direction of an int

-----------------------------------------------------------------------------------------------

// Function returning pointer
#include <iostream>
using namespace std;

int *fun();  //fun declaration

int main()
{
    int *p;
    p = fun();
    cout << "\n" << p << endl;
    cout << *p << endl;
    return 0;
}

int *fun()
{
    int i = 20;
    return(&i);
}

OUTPUT:


No comments:

Post a Comment