# Can we Use a Pointer for Subscript to Access an Array in C?

«
»
Question: Can we Use Pointer for Subscript to Access an Array in C Programming?

Answer: Subscript operator ‘[]’ have higher precedence than indirection operator ‘*’, but in fact, both are same. Let’s see an example,

`    int max = {1,2,3,4,5};   /* max is an array of 5 integers */`

Well! In order to access elements of array ‘max[]’ using pointer, we must know type of array ‘max[]’ so we can declare and initialize pointer of same type to use it to access array ‘max[]’. So, what’s the type of array ‘max[]’? ‘max’ is an array of 5 something which happen to be 5 integers. Address of first integer ‘max’, let’s say,

`    1000`

which is calculated as,

`    1000 + 0 * 4        /* type 'int' takes 4 bytes */`

address of 2nd element ‘max’ is calcuated as,

`    1000 + 1 * 4        /* 1000 is the base address of the array 'max[]' */`

and so on. Since each address points to an integer, therefore type of array is pointer-to-integer. So,

`    int *pi;        /* 'pi' is pointer to type int */`

and its initialization

```    pi = array;
/* value of array, pointer constant, is copied into pointer 'pi' */```

allows us to access the elements of array ‘max[]’. Now, ‘pi’ points to the first element, ‘max’, of array. On performing indirection on the ‘pi’, value at the location pointed to by pi is obtained. For example,

`    *pi;        /* value of 'max' is obtained */`

Next, how can we obtain values of successive elements of array ‘max[]’? We’re very well familiar with pointer arithmetic and here we would implement it to learn how simple it’s to access the array elements using pointer! What will happen when

`    *(pi++);        /* which is same as *(pi + 1) */`

Firstly, expression in parenthesis is evaluated, 1 in the exp. (pi + 1) is scaled by the size of integer as

`    (pi + 1 * 4); equals (pi + 4);`

which results in pointer to 2nd element ‘max’ in array ‘max[]’. Now indirection is performed on the pointer

`    *(pi + 4);        /* indirection performed */`

which results in value of pointed to location i.e. value 2. This way, we can use pointer ‘pi’ to access elements in the array ‘max[]’.

Consider the fragment of code below to access the array ‘max[]’,

```    int max = {1,2,3,4,5};
int *pi;
int i;

for (i = 0, pi = max; pi < &max; pi++, i++)
printf("max[%d] has value %d\n", i, *pi);```

Remember the Rules of Compatibility of Pointers while declaring and initializing pointer to access an array.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials. 