C Accessing array



In the previous chapters we have already learnt about the basic concepts of array and how to create and initialize array. In this chapter we will be learning how we will be accessing array.

C Programming : Accessing Array

  1. We all know that array elements are randomly accessed using the subscript variable.
  2. Array can be accessed using array-name and subscript variable written inside pair of square brackets [].

Consider the below example of an array –

accessing array

In this example we will be accessing array like this –

arr[3]  = Third Element of Array
arr[5]  = Fifth Element of Array
arr[8]  = Eighth Element of Array

whereas elements are assigned to an array using below way –

arr[0]  = 51
arr[1]  = 32
arr[2]  = 43
arr[3]  = 24
arr[4]  = 5
arr[5]  = 26

Program #1 : Accessing array

#include<stdio.h>
#include<conio.h>

void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
    for(i=0; i<=5; i++) {
         printf("\nElement at arr[%d] is %d",i,arr[i]);
	}
getch();
}

Output :

Element at arr[0] is 51
Element at arr[1] is 32
Element at arr[2] is 43
Element at arr[3] is 24
Element at arr[4] is 5
Element at arr[5] is 26

How a[i] Works ?

We have following array which is declared like this –

int arr[] = { 51,32,43,24,5,26};

As we have elements in an array, so we have track of base address of an array. Below things are important to access an array –

ExpressionDescriptionExample
arrIt returns the base address of an arrayConsider 2000
*arrIt gives zeroth element of an array51
*(arr+0)It also gives zeroth element of an array51
*(arr+1)It gives first element of an array32

So whenever we tried accessing array using arr[i] then it returns an element at the location *(arr + i)

Accessing array a[i] means retrieving element from address (a + i).

We have listed out some of our observations and conclusions

arr[i]    = 5
*(arr+i)  = 5
*(i+arr)  = 5
i[arr]    = 5

all of the above notations yields same result. lets prove it using below program –

Program #2 : Accessing array

#include<stdio.h>
#include<conio.h>

void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
    for(i=0; i<=5; i++) {
         printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i),i[arr]);
	}
getch();
}

Output :

51 51 51 51
32 32 32 32
43 43 43 43
24 24 24 24
5 5 5 5
26 26 26 26