Arrays and Pointers

Arrays and Pointers

Published by: Nuru

Published date: 21 Jun 2021

Arrays and Pointers Photo

Arrays and Pointers

In C, there is a strong relationship between arrays and pointers. Any operations that can be achieved by array subscripting can also be done with pointers. The pointer version will, in general, be faster but for the beginners somewhat harder to understand.

An array name is itself is an address or pointer value, so any operation that can be achieved by array subscripting can also be done with pointers as well. Pointers and arrays are almost synonymous in terms of how they are used to access memory, but there are some important differences between them. A pointer is fixed. An array name is a constant pointer to the first element of the array. The relation of pointer and array is presented in the following tables:

 

array and pointer

Array and Pointer

Pointer and one-dimensional array

The elements of an array are stored in contiguous memory locations.

Suppose we have an array arr[5] of type int.
int arr[5]={6,9,12,4,8};
This is stored in memory as

Array and Pointer

Here 5000 is the address of the first element, and since each element (type int) takes 2 bytes so the address of the next element is 5002, and so on. The address of the first element of the array is also known as the base address of the array.

Program to print the value of array element using pointer
#include
#include
void main()
{
int arr[100],i,n;
printf("How many elements are there: ");
scanf("%d",&n);
for(i=0;i {
printf("\n Enter element: ");
scanf("%d",(arr+i));
}
printf("\n Printing array element:");
for(i=0;i {
printf("\n %d",*(arr+i));
}
getch();
}

Output:

Array and Pointer

Pointer with two-dimensional arrays

In a two-dimensional array, we can access each element by using two subscripts, where the first subscript represents row number and the second subscript represents the column number. The elements of the 2-D array can be accessed with the help of pointer notation. Suppose arr is a 2-D array, then we can access any element arr[i][j] of this array using the pointer expression *(*(arr+i)+j).

Example
1. Write a program to read any 2 by 3 matrix and display its element in appropriate format.
#include
#include
void main()
{
int arr[2][3],i,j;
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("\n Enter elements of matrix: ");
scanf("%d",&arr[i][j]);
}
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",*(*(arr+i)+j));
}
printf("\n");
}
getch();
}

Output:

Array and Pointer