 # 2-Dimensional (2 D) Array: memory aspect

Ankur Kulhari

A 2-D array can be logically think of array of arrays as shown below: Fig. 1: Logical view of 2 D array

Let’s have a program to understand 2-D array better:

```#include &lt;stdio.h&gt;

int main() {
int a={1,2,3,4,5,6};
printf("a=%p\t&a=%p\n",a,&a);
printf("a=%p\t&a=%p\n",a,&a);
printf("a=%p\t&a=%p\n",a,&a);
printf("a=%p\t&a=%p\n",a,&a);
return 0;
}
```
###### output
```a=0x7ffd8da57dc0     &a=0x7ffd8da57dc0
a=0x7ffd8da57dc0  &a=0x7ffd8da57dc0
a=0x7ffd8da57dc8  &a=0x7ffd8da57dc8
a=0x7ffd8da57dd0  &a=0x7ffd8da57dd0
Note: these values may vary, as the allocated memory location may change every time when a program is executed.
```

The memory view of above program can be analyzed as shown in the figure below: Fig. 2: Memory view of 2-D array Fig. 3: Logical View of 2-D array with respect to memory

###### Accessing elements of 2-D array

Similar to 1-D array, 2-D array can also be accessed in same way as- a[i][j] = *(*(a+i)+j), which can be analyzed as:

```Step1: Divide the array into i equal parts.
Step2: Each part will contain j elements.
Step3: a is pointing to the starting of outer block.
Step4: The pointer will move block wise, i.e a+1=a+i*size of an element of the array
Step5: *a will move you to one block inner, i.e. *a+1 = a+size of an element of the array
```
###### Example
```int a = {2,4,1,6,3,8}
```
###### explanation

Dividing the array into 2 parts (each containing 3 elements) Fig. 4: Dividing array into 2 blocks Fig. 5: a+1 will point to the next block

a is pointing to the outer block. Inner blocks are invisible. Fig. 6: *a will move one block inner

*a will move one block inside, i.e now the inner blocks are visible Fig. 6: *a will move one block inner

*a+1 will be Fig. 7: *a will move one block level inner

**a will be Fig. 8: **a will give the value at *a

**a+1 will be: precedence of Pointer operator is higher than addition (+) operator so, first **a will be resolved and, **a =2, then **a+1 = (2)+1=3 Fig. 9: **a+1 = (**a)+1 = 2+1=3

###### Exercise 1 of 2D array
```#include&lt;stdio.h&gt;

int main() {
int arr={1,5,12,34,21,60};
int *p1;
int (*p);
p=arr;
p1=arr;
printf("*arr=%u, arr+1=%u, *arr+1=%u, **arr=%u\n",*arr,arr+1,*arr+1,**arr);
printf("*(*p+1)=%u, *p1+1=%u, *(p1+1)=%u, **(p+1)=%u",*(*p+1), *p1+1,*(p1+1),**(p+1));
return 0;
}
```
###### output
```*arr=3216547240, arr+1=3216547248, *arr+1=3216547244, **arr=1
*(*p+1)=5, *p1+1=2, *(p1+1)=5, **(p+1)=12
``` Fig. 10: Memory view of exercise 1