Nearby lessons
55 of 124C - Access Array Elements
How to access and modify array elements in C using the subscript operator [], why arr[i] is really *(arr + i), and how to stay inside the array bounds.
Reading Elements
Put the index in square brackets after the array name. Any integer expression works as the index:
Example01
Writing to Elements
The same arr[i] expression on the left of = stores a value. An array element behaves exactly like an ordinary variable:
Example02
Accessing Every Element with a Loop
The for loop is the natural partner of an array. Note the condition i < size, never i <= size:
Example03
What [] Really Does
The array name is the address of the first element. The subscript operator is defined as pointer arithmetic:
arr[i] means *(arr + i) — "go i elements past the start, then read what is there".
Example04
Why 2[nums] Compiles
In simple words: because
arr[i] is defined as *(arr + i), and addition is commutative, *(2 + nums) is the same as *(nums + 2). So 2[nums] works. It is a famous C curiosity — never write it in real code, but it proves that [] is pure pointer arithmetic.Validating an Index
When the index comes from the user, check it yourself. C will not:
Example06
Common Mistakes
i <= sizein the loop condition — reads one element past the end every single time.- Starting at
i = 1— silently skips the first element. - Using
&when reading —printf("%d", &nums[0])prints an address, not the value. - Forgetting
&when scanning —scanf("%d", nums[i])crashes; it needs&nums[i]. - Negative indexes —
arr[-1]compiles and reads memory before the array.
The classic off-by-one:
for (i = 0; i <= 5; i++) on int a[5] touches a[5], which does not exist. Use i < 5. This single character is responsible for an enormous share of real-world C bugs.📝 Key Takeaways
- arr[i] both reads and writes element i.
- arr[i] is exactly equivalent to *(arr + i).
- Valid indexes run from 0 to size - 1.
- Because arr[i] == *(arr+i), the odd form i[arr] also compiles.
- Always validate an index that comes from user input.
🧠 Test Your Knowledge
4 QuestionsProgress: 0 / 4