Introduction to Arrays in C
An array in C is a collection of elements of the same data type stored in contiguous memory locations. You can access each element using an index.​
Example:
int numbers[5] = {10, 20, 30, 40, 50};
Here, numbers[0] accesses the first element, which is 10.​
The Equivalence of array[i] and i[array]
In C, the expressions array[i] and i[array] are functionally equivalent. This is because the array subscript operator [] is defined in terms of pointer arithmetic:​
array[i] == *(array + i) i[array] == *(i + array)
Since addition is commutative, array + i is the same as i + array, making array[i] and i[array] interchangeable.​
How Array Indexing Works in C
When you use the subscript operator [], the compiler interprets it as a pointer addition followed by dereferencing.​
Example:
int arr[3] = {1, 2, 3};
- arr[1] is interpreted as *(arr + 1), which accesses the second element.​
- 1[arr] is interpreted as *(1 + arr), which also accesses the second element.​
Both expressions yield the same result.
Understanding Pointer Arithmetic
In C, when you add an integer to a pointer, the pointer moves by that integer multiplied by the size of the data type it points to.​
Example:
int arr[3] = {1, 2, 3}; int *ptr = arr;
- ptr + 1 moves the pointer to the second element.​
- *(ptr + 1) accesses the value at the second element, which is 2.​
This behavior underpins the equivalence of array[i] and i[array].​
Practical Examples
Example 1:
#include <stdio.h> int main() { int marks[] = {70, 60, 80, 45, 73}; printf("%d\n", marks[2]); // Outputs 80 printf("%d\n", 2[marks]); // Also outputs 80 return 0; }
Output:
80 80
This program shows two ways to access the same array element in C. The array marks holds five numbers. Both marks[2] and 2[marks] give the third value, which is 80. C allows this because of how arrays and pointers work.
Example 2:
#include <stdio.h> int main() { char str[] = "Sanfoundry"; printf("%c\n", str[1]); // Outputs a printf("%c\n", 1[str]); // Also outputs a return 0; }
Output:
a a
This program demonstrates accessing characters in a string using two equivalent methods. The string str contains “Sanfoundry”. Both str[1] and 1[str] return the second character, which is ‘a’. This works because str[i] is the same as *(str + i) in C.
Common Misconceptions
- Misconception: i[array] is invalid syntax.​​ Reality: As shown, i[array] is valid and equivalent to array[i].​​
- Misconception: Arrays and pointers are the same.​​ Reality: While arrays decay to pointers in expressions, they are not the same. For instance, sizeof(array) gives the total size of the array, whereas sizeof(pointer) gives the size of the pointer itself.​
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Apply for Computer Science Internship
- Check C Books
- Practice BCA MCQs
- Check Computer Science Books
- Apply for C Internship