0

I am a totally beginner in programming and I have a question in the following code it's about creating a dynamic multidimensional array I don't understand the reason of p what's the function of it here

#include <iostream>
using namespace std;

void print2DArr(int** arp,int *ss,int nrows)
{
    for(int i=0;i<nrows;i++){
        for(int j=0;j<ss[i];j++){
            cout << arp[i][j] <<" ";
        }
        cout << endl;
    }
}

void main()
{
    int count;
    cout << "How many arrays you have?\n";
    cin >> count;
    int **arrs = new int*[count];
    int *sizes = new int[count];
    //int *arrs[3];//static array of pointers
    for(int i=0;i<count;i++)
    {
        int size;
        cout << "Enter size of array " << (i+1) << endl;
        cin >> size;
        sizes[i]=size;
        int *p = new int[size];
        arrs[i] = p;
        //arrs[i] = new int[size];
        cout << "Enter " << size << " values\n";
        for(int j=0;j<size;j++)
            //cin >> p[j];
            cin >> arrs[i][j];
    }

    print2DArr(arrs,sizes,count);

    //delete (dynamic de-allocation)
    for(int i=0;i<count;i++)
        delete[] arrs[i];
    delete[] arrs;


}
1
  • The accuracy of the initial prompt in your program couldn't be more accurate. Props for that. Once you get a handle on this, pat yourself on the back, then realize std::vector<> would be a logical choice for implementing this with modern C++. Commented Jan 15, 2015 at 6:19

2 Answers 2

3

It's variable that does not do a whole lot. You can replace the lines

    int *p = new int[size];
    arrs[i] = p;

with

    arrs[i] = new int[size];

without any problem.

Sign up to request clarification or add additional context in comments.

Comments

0

you are creating a dynamically sized int array in your for loop. p is pointing to that newly created int array. You can then assign p (the adress of your new int array) to the i-th position of your array of pointers to int array (that's what the next statement does: arrs[i]=p).

Therefore your structure looks like:

arrs (array of pointers to int arrays):
- arrs0: pointing to int array 1 at adress 4711
- arrs1: pointing to int array 2 at adress 9876

sizes (array of int's) - holding the sizes of your int arrays (not of your array of pointers to int arrays!)
- 0: 2
- 1: 3

int array 1 (adr 4711)
- 0: 17
- 1: 23

int array 2 (adr 9876)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.