Previous | Home | Next |
How arrays and pointer are linked ?
As we know that a pointer is a variable that contains the address the another variable. That is, a pointer a special kind of variable that is containing the address of another variable and we can define a pointer in the following manner,
Which means that the ptr is a pointer type variable that is pointing to a address where an integer type value is stored.
Also, we know that in an array elements are stored in sequential manner in which the very first index corresponds to the base address of first element which acts as a base address of the entire array, i.e. we can say that an array is a kind of pointer itself in which elements are stored according to their addresses.
We can declare a pointer to an array in the following way :
int *ptr;
ptr = &a[0];
In above example we have defined an array of five elements and a pointer is defined which is pointing to the first element of the array
How to use 2-D array with pointer
The following example takes a two dimensional array as input from the user and display its contents via using pointer.
#include<conio.h>
void main()
{
int i=0, j=0;
int arr[3][3];
int *ptr1;
ptr1 = &arr[0][0];
clrscr();
printf("\nEnter the elements of the array :")
for(int i=0; i<=2; i++)
{
for(int j=0; j<=2; j++)
{
scanf("\n%d", &arr[i][j]); /* taking the input 2-D array or matrix from the user */
}
}
printf("Following are the elements of the array :");
for(int i=0; i<=2; i++)
{
for(int j=0; j<=2; j++)
{
printf("\n%d", *ptr1); /* diplaying the content of the matrix */
ptr1++;
}
}
getch();
}
Output : The output of the following program would be as follows :
Enter the elements of the array :
1 2 3
4 5 6
7 8 9
Following are the elements of the array :
1 2 3
4 5 6
7 8 9
Previous | Home | Next |