2-Dimensional (2 D) Array: memory aspect

Ankur Kulhari

A 2-D array can be logically think of array of arrays as shown below:

2 D array

Fig. 1: Logical view of 2 D array

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

#include <stdio.h>

int main() {
	int a[3][2]={1,2,3,4,5,6};
	printf("a=%p\t&a=%p\n",a,&a);
	printf("a[0]=%p\t&a[0][0]=%p\n",a[0],&a[0][0]);
	printf("a[1]=%p\t&a[1][0]=%p\n",a[1],&a[1][0]);
	printf("a[2]=%p\t&a[2][0]=%p\n",a[2],&a[2][0]);
	return 0;
}
output
a=0x7ffd8da57dc0     &a=0x7ffd8da57dc0
a[0]=0x7ffd8da57dc0  &a[0][0]=0x7ffd8da57dc0
a[1]=0x7ffd8da57dc8  &a[1][0]=0x7ffd8da57dc8
a[2]=0x7ffd8da57dd0  &a[2][0]=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:

Memory view of 2-D array

Fig. 2: Memory view of 2-D array

2-D array logical view

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][3] = {2,4,1,6,3,8}
explanation

Dividing the array into 2 parts (each containing 3 elements)

2-D array

Fig. 4: Dividing array into 2 blocks

2 D array

Fig. 5: a+1 will point to the next block

a is pointing to the outer block. Inner blocks are invisible.
2-D array

Fig. 6: *a will move one block inner

*a will move one block inside, i.e now the inner blocks are visible
2-D array

Fig. 6: *a will move one block inner

*a+1 will be
2D array

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

**a will be
2D array

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
2D array

Fig. 9: **a+1 = (**a)+1 = 2+1=3

Exercise 1 of 2D array
#include<stdio.h>

int main() {
	int arr[3][2]={1,5,12,34,21,60};
	int *p1;
	int (*p)[2];
	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
2D array

Fig. 10: Memory view of exercise 1

Comments 1

  1. Pingback: Pointer in C/C++ - Study Korner

What do you think about the article?

This site uses Akismet to reduce spam. Learn how your comment data is processed.