Reputation: 33
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;
}
Upvotes: 0
Views: 111
Reputation: 1651
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)
Upvotes: 0
Reputation: 206567
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.
Upvotes: 3