Dynamic 2D Array in C++ with explanation
Dynamic 2D Array In C++
Try to
create integer 2D array of 4 row and 3 columns.
Code snippet:
int** a = new int* [4];//line1
for(int i = 0;
i < 4; i++) {//line2
a[i] = new int[3];//line3
} //line4
Explanation:
Let, Address of a is 0x100 and size of int is 4.
So, Address of a[0] is 0x100, address of a[1] is 0x104,
address of a[2] is 0x108 and so on.
a[0] a[1] a[2] a[3]
0x100 0x104 0x108
0x10C
1st Iteration of line3. Assume receives starting address
is 0x500. So, three address is 0x500,0x504,0x508.
a[0] = 0x500;
0x500 0x504 0x508
Updated value of a is:
0x500
|
0x100 0x104 0x108 0x10C
2nd Iteration of line3. Assume receives starting address is
0x600. So, three address is 0x600,0x604,0x608.
a[1] = 0x500;
0x600 0x604 0x608
Updated value of a is:
0x500
|
0x600
|
0x100 0x104 0x108 0x10C
3rd Iteration of line3. Assume receives starting address is
0x700. So, three address is 0x700,0x704,0x708.
a[2] = 0x700;
0x700 0x704 0x708
Updated value of a is:
0x500
|
0x600
|
0x700
|
0x100
0x104 0x108 0x10C
4th Iteration of line3. Assume receives starting address is
0x800. So, three address is 0x800,0x804,0x808.
a[3] = 0x800;
0x800 0x804
0x808
Updated value of a is:
0x500
|
0x600
|
0x700
|
0x800
|
0x100 0x104 0x108 0x10C
Try to put value in array from 1 to 12.
Code snippet
int x = 0; //line5
for (int i = 0;
i < 4; i++) {//line6
for (int j = 0; j < 3; j++) {//line7
a[i][j] = ++x;//line8
}
}
a[i][j] -> *(*(a+i)+j)
For 1st
iteration of i:
For 1st iteration of j:
a[0][0] -> *(*(a+0)+0)
a= 0x100;
a+0 ->0x100;
*(a+0) -> 0x500
(*(a+0)+0) ->0x500
*(*(a+0)+0) ->1
Then, a[0][0] = 1;
For
2nd iteration of j:
a= 0x100;
a+0 ->0x100;
*(a+0) -> 0x500
(*(a+0)+1) ->0x500+1*sizeof(int)=0x500+4=0x504
*(*(a+0)+1) = 2
Then, a[0][1] = 2;
Going so on.
Let, 4th iteration of i and
3rd iteration of j
a[3][2] = 12;
a[3][2] -> *(*(a+3)+2)
a=0x100;
a+3 ->
0x100 + 3*sizeof(int) = 0x100 + 3*4 = 0x10C
//Hex value
0x10C = Decimal value 112.
*(a+3) = *(0x10C)
-> 0x800
(*(a+3)+2) =
0x800 + 2*sizeof(int) = 0x800+2*4=0x808
*(*(a+3)+2)
= 12 // value 0x808 address
1
|
2
|
3
|
0x500 0x504
0x508
4
|
5
|
6
|
0x600 0x604
0x608
7
|
8
|
9
|
0x700 0x704 0x708
10
|
11
|
12
|
0x800 0x804
0x808
Comments
Post a Comment