Pointer to 2D Array in C
Notes:
Pointer to Two Dimensional ( 2D ) Array in C Programming Language:
- Pointer is a variable which holds the address of another memory location
- Array is a contiguous collection of homogeneous data elements
Declaring and initializing a 2D array:
datatype arrayName[rows][cols] = {set of blocks separated by comma};
Ex:
int numbers[2][2] = { {1,2} , {3,4} };
Note:
arrayName is implicitly a pointer to the 0th row of the array
Ex:
numbers is implicitly a pointer to the 0th row of the numbers array
Accessing array elements using arrayName and its rindex & cindex:
There are 2 different ways in which we can access each element in an array using arrayName and its rindex & cindex
1. Subscript notation: arrayName[rindex][cindex] Ex: numbers[0][0]
2. Pointer notation: *(*(arrayName + rindex) + cindex) Ex: *(*(numbers + 0) + 0)
Declaring and initializing a pointer to a 2D array:
datatype (*pointerName)[cols] = arrayName;
Ex:
int (*iptr)[2] = numbers;
Accessing array elements using pointerName and element rindex & cindex:
There are 2 different ways in which we can access each element in an array using pointerName and its rindex & cindex
1. Subscript notation: pointerName[rindex][cindex] Ex: iptr[0][0]
2. Pointer notation: *(*(pointerName + rindex)+cindex) Ex: *(*(iptr + 0)+0)
Example Code:
#include <stdio.h>
int main()
{
int numbers[2][2] = {
{1,2},
{3,4}
};
int (*iptr)[2] = numbers;
printf("%d\n", numbers[0][0]);
printf("%d\n", numbers[0][1]);
printf("%d\n", numbers[1][0]);
printf("%d\n", numbers[1][1]);
printf("\n");
printf("%d\n",*(*(numbers+0)+0));
printf("%d\n",*(*(numbers+0)+1));
printf("%d\n",*(*(numbers+1)+0));
printf("%d\n",*(*(numbers+1)+1));
printf("\n");
printf("\n");
printf("%d\n", iptr[0][0]);
printf("%d\n", iptr[0][1]);
printf("%d\n", iptr[1][0]);
printf("%d\n", iptr[1][1]);
printf("\n");
printf("%d\n",*(*(iptr+0)+0));
printf("%d\n",*(*(iptr+0)+1));
printf("%d\n",*(*(iptr+1)+0));
printf("%d\n",*(*(iptr+1)+1));
printf("\n");
return 0;
}