lundi 26 octobre 2015

Dereferencing double pointer, triple pointers, and so on

Below is a sample program I created to play around with pointers.

#include <iostream>
using namespace std;

void addOne(int** ptr);
void addTwo(int*** ptr);
void addThree(int**** ptr);
void addFour(int***** ptr);

int main()
{
    int* ptr = nullptr; 
    int x = 1; 
    ptr = &x;

    cout << "Original value of x: " << *ptr << endl;

    addOne(&ptr);

    cin.get();
    return 0;
}

void addOne(int** ptr)
{
    **ptr += 1;
    cout << "After adding 1: " << **ptr << endl;
    addTwo(&ptr);
}

void addTwo(int*** ptr)
{
    ***ptr += 2;
    cout << "After adding 2: " << ***ptr << endl;
    addThree(&ptr);
}

void addThree(int**** ptr)
{
    ****ptr += 3;
    cout << "After adding 3: " << ****ptr << endl;
    addFour(&ptr);
}

void addFour(int***** ptr)
{
    *****ptr += 4; 
    cout << "After adding 4: " << *****ptr << endl;
}

The program above will give me the following output:

Original value of x: 1
After adding 1: 2
After adding 2: 4
After adding 3: 7
After adding 4: 11

Now focus on the addFour function:

void addFour(int***** ptr)
{
    *****ptr += 4; 
    cout << "After adding 4: " << *****ptr << endl;
}

Now what I did was I reduced the number of *s in the addFour function by doing this:

void addFour(int***** ptr)
{
   ****ptr += 4; 
   cout << "After adding 4: " << ****ptr << endl;
}

When I did the above code, it gave me the following output:

Original value of x: 1
After adding 1: 2
After adding 2: 4
After adding 3: 7
After adding 4: 010EFDE0

My question then is, what is the following statements doing since I reduced the number of *s:

****ptr += 4; 
cout << "After adding 4: " << ****ptr << endl;

Can someone please explain this for me?

Aucun commentaire:

Enregistrer un commentaire