greetings my friends ,
lets say we have an two dimensional array of arr[10][20];
int ** arr;
arr = new int*[10] ; // this means we are initialising memory for 10 pointers of int type
for(int i=0 ; i < 10 ; i++)
{
arr = new int[i][20]; //.......................... eqn 1
}
or
int ** arr;
arr = new int*[10] ;
for(int i=0 ; i < 10 ; i++)
{
arr[i] = new int[20]; // different from one .
}
More explanation : (read it completely )
Ok, let me explain with littile more detail, lets say we have an array of arr[10][20] . what does it actually means ?
one of the meaning of it is that we have 10 arrays of size of 20 each.
now i ask you how do you initialise 1-d array?
int *arr;
arr = new int[20];
right ?
that means we require one pointer of int type to initialise an array of size 20 in heap memory.
then how much pointer of int type we require to initialise 10 arrays with each of size 20 ?
yes you are correct it 10 pointers.
The only difference between initialisation of 1-d array and 2-d array is that in 2-d array the pointer for initialisation of array are also taken in heap memory by using the following instruction.
arr = int*[10];
it means we are initialising 10 pointers in heap memory i.e we give memory to n pointer in heap memory.
these pointers are : arr[0],arr[1] , arr[2] , arr[3] and so on ......
again consider how 1-d array is initialised?
int * t;
t = new int[10].
in place of t we have arr[0] , arr[1], like this .
so we can initialise like this :
for(int i =0 ; i < 10 ; i++)
{
arr[i] = new int [20];
}
another defined way which the compiler understands right is :
for(int i =0 ; i < 10 ; i++)
{
arr = int[i][20];
}
Comments
Post a Comment