Taylor's Blog

Atypical ramblings

A pointer to a pointer to a pointer to a…

This is a small slice of code adapted form a school project I was working on that I feel really helps explain the concept of pointers with arrays. It’s a 2-D¬†array: an array of pointers, each of which¬†points to an array of ints. It essentially forms a 2×2 grid (but you can make it other sizes too).

//function prototype
void fillMatrix(int** myArray, int size);

//main() function
int main()
{
    const int SIZE = 4;
    int** p_myArray = new int*[2]; //make the initial x-axis which has two slots
    p_myArray[0] = new int[2]; //make the 1st y-axis which has two slots
    p_myArray[1] = new int[2]; //make the 2nd y-axis which has two slots

    //alternatively, you could do it this way (if making a 3x3 grid with SIZE=3):
    /*
    int** p_myArray = new int*[3];                                     
    for (int i = 0; i < 4; i++) //for every x-axis...
    {
        p_myArray[i] = new int[3]; //make a y-axis three slots big                  
    }
    */

    //function call
    fillMatrix(p_myArray, SIZE);
}

//function definition
void fillMatrix(int** myArray, int size)
{
 cout << "Please enter " << size << " integers to fill the array." << endl;
 for (int i = 0; i < (2); i++)
     {
         cin >> myArray[0][i];
     }
}

Just to help visualize it, here is what a 2-D, 5×5 array looks like:

M75kn

Updated: January 21, 2016 — 4:06 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

Taylor's Blog © 2015