Answer: Subscript operator ‘[]’ have higher precedence than indirection operator ‘*’, but in fact, both are same. Let’s see an example,
int max[5] = {1,2,3,4,5}; /* max[5] 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[5]’ is an array of 5 something which happen to be 5 integers. Address of first integer ‘max[0]’, let’s say,
1000
which is calculated as,
1000 + 0 * 4 /* type 'int' takes 4 bytes */
address of 2nd element ‘max[1]’ 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[0]’, of array. On performing indirection on the ‘pi’, value at the location pointed to by pi is obtained. For example,
*pi; /* value of 'max[0]' 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[1]’ 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[5] = {1,2,3,4,5}; int *pi; int i; for (i = 0, pi = max; pi < &max[5]; 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.
- Check Computer Science Books
- Apply for C Internship
- Practice Computer Science MCQs
- Check C Books
- Watch Advanced C Programming Videos