🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Array Index and Bounds
Chapter 7, Lecture 3 of the free C programming course: read and write single elements, use expressions as subscripts, and learn why C never checks the bounds for you.
Once an array exists, you work with it one element at a time, and the C array index is the key that selects each element. Understanding the index, and the valid range it must stay inside, separates safe firmware from firmware that corrupts its own memory. This lecture is part of our free C programming course and the free embedded C course, and it focuses on the habits that matter most in embedded C programming, where one stray write can hang a device in the field.
What You Will Learn
- How to read and write one element with the subscript operator
- Why the lower bound is 0 and the upper bound is size minus 1
- Which expressions are legal as a C array index
- That an array element behaves exactly like a normal variable of its type
- What happens when an index goes outside the array, and why the compiler stays silent
- A simple, reusable pattern for checking an index before using it
Prerequisites
- Lectures 1 and 2 of this chapter
- Arithmetic, increment and compound assignment operators (
++,+=) - Writing a function with parameters and a return value
Selecting an Element with the C Array Index
You pick an element by writing the array name followed by the index in square brackets. For an array declared as int reg[5]; the five valid elements are reg[0], reg[1], reg[2], reg[3] and reg[4]. The smallest legal index, 0, is the lower bound. The largest, 4, is the upper bound, always one less than the size.
Any Integer Expression Can Be an Index
The subscript does not have to be a literal number. It can be any expression that produces an integer: a constant, a variable, arithmetic on variables, or the value returned by a function call. That flexibility is what makes loops over arrays possible.
| Index form | Example | Notes |
|---|---|---|
| Integer constant | reg[3] | Fixed position, such as a specific register slot |
| Integer variable | reg[i] | The workhorse of every loop |
| Arithmetic expression | reg[i + j], reg[2 * j] | Computed positions, such as every second element |
| Function result | reg[get_slot()] | The function must return an integer type |
| Expression with side effect | reg[i++] | Uses i, then increments it; legal but easy to misread |
An Array Element Is Just a Variable
The most useful mental shortcut is this: reg[2] can be used anywhere a normal int variable could be used. You can print it, assign to it, increment it, add to it or pass it to a function. If the array is a float array, each element behaves like a float, and so on.
| Operation | Plain variable | Array element |
|---|---|---|
| Assign | count = 25; | reg[4] = 25; |
| Increment | count++; | reg[4]++; |
| Add to it | total += 200; | reg[0] += 200; |
| Read it | printf(“%d”, count); | printf(“%d”, reg[4]); |
| Input it | scanf(“%d”, &count); | scanf(“%d”, ®[1]); |
Notice the & in scanf: you pass the address of one element, exactly as you would for a single variable.
Try It: Indexing in Action
This program shows constants, variables and expressions as indices. It also edits elements in place, and it includes a small function that refuses invalid indices instead of reading them.
#include <stdio.h>
#define LEN 5
/* returns 1 and fills *out when idx is valid, else returns 0 */
int safe_read(const int *arr, int len, int idx, int *out)
{
if (idx < 0 || idx >= len) {
return 0;
}
*out = arr[idx];
return 1;
}
int main(void)
{
int reg[LEN] = {10, 20, 30, 40, 50};
int i = 1, j = 2, val;
printf("reg[3] = %d\n", reg[3]);
printf("reg[i] = %d\n", reg[i]);
printf("reg[i + j] = %d\n", reg[i + j]);
printf("reg[2 * j] = %d\n", reg[2 * j]);
reg[4] = 25;
reg[4]++;
reg[0] += 200;
printf("after edits: reg[0]=%d reg[4]=%d\n", reg[0], reg[4]);
if (safe_read(reg, LEN, 5, &val)) {
printf("reg[5] = %d\n", val);
} else {
printf("index 5 rejected (valid range 0..%d)\n", LEN - 1);
}
if (safe_read(reg, LEN, -1, &val)) {
printf("reg[-1] = %d\n", val);
} else {
printf("index -1 rejected\n");
}
return 0;
}
gcc -Wall -Wextra -std=c11 -o index_demo index_demo.c
./index_demo
Expected output:
reg[3] = 40
reg[i] = 20
reg[i + j] = 40
reg[2 * j] = 50
after edits: reg[0]=210 reg[4]=26
index 5 rejected (valid range 0..4)
index -1 rejected
Walking Through the Output
reg[i + j]isreg[3]because 1 plus 2 is 3, so it prints the same 40 as the first line.reg[2 * j]isreg[4], the last element, which still holds 50 at that point.- After the edits, element 4 went from 50 to 25 and then to 26, and element 0 went from 10 to 210.
- The helper function compares the index with 0 and with the length before it touches the array, so the two bad indices never reach the memory.
The const int *arr parameter is how a function receives an array; the next chapters explain that notation fully. For now, read it as “the function gets to look at the array without being allowed to change it”.
C Does Not Check Array Bounds
Here is the fact every embedded programmer must memorise: in C, nothing checks your index at run time. If you declare int reg[5] and write reg[5] = 1, reg[10] = 1 or reg[-1] = 1, the compiler normally accepts the line without an error. The program then reads or writes memory that belongs to something else. The language calls this undefined behaviour, which means anything may happen: nothing visible, a wrong value, a crash, or a bug that appears weeks later in unrelated code.
Why this is so dangerous on microcontrollers: there is usually no operating system and no memory protection unit configured to stop the stray write. The overwrite silently changes some other variable, and the symptom appears far from the cause. Buffer overflows from unchecked indices are also one of the most common routes for security bugs in connected devices.
Who Is Responsible?
You are. The compiler can only warn you in simple cases, such as a constant index that is obviously too large, and only when warnings are enabled. When the index comes from a variable, user input or a received packet, the only protection is a check you write yourself, like the safe_read() function above. A C array index that arrives from a sensor, a keypad, a configuration file or a radio packet should be treated as hostile until it has been range-checked, because an attacker or a noisy wire can send any number at all.
A Reusable Bounds-Check Pattern
Follow one habit: whenever an index is not a compile-time constant, test it against the size before use.
if (idx >= 0 && idx < LEN) {
reg[idx] = new_value;
} else {
/* report an error, clamp the value, or ignore the request */
}
If the index type is unsigned, the “greater than or equal to zero” half is always true, and a single comparison idx < LEN is enough. Choosing unsigned indices for array positions therefore removes one whole class of bug.
Common Mistakes with the C Array Index
- Writing
arr[size]to reach “the last element”; the last element isarr[size - 1] - Looping with
i <= sizeinstead ofi < size, which touches one element too many - Mixing up the index and the value stored at that index, for example using
arr[arr[i]]by accident - Using an index received from a sensor or a serial port without validating it
- Reading
reg[i++]inside a larger expression and losing track of whenichanges
Safe C Array Index Best Practices
A safe C array index is one that has been proven to lie between 0 and size minus 1 before the access happens. These habits make that proof routine.
- Treat every non-constant index as untrusted until it has passed a range check
- Keep index arithmetic simple; put
i++on its own line - Prefer
<against the size in loops, never<= - Use unsigned types for indices when negative values make no sense
- Turn on compiler warnings and consider a static analyser for safety-critical firmware
- During testing on a PC, build with
-fsanitize=address,undefinedto catch out-of-range accesses immediately
Summary and Key Takeaways
Key takeaways
- Select an element with
name[index]; valid indices run from 0 to size minus 1 - The index may be any integer expression, including variables and function results
- An array element can be used wherever a variable of the same type is allowed
- C performs no run-time bounds checking; an invalid index is undefined behaviour
- Protect every computed C array index with an explicit check
Frequently Asked Questions
What are the valid indices for an array of size N in C?
Zero through N minus 1. An array of size 5 accepts indices 0, 1, 2, 3 and 4 only.
Does C give an error for an out-of-bounds array index?
Usually not. The compiler may warn for an obvious constant index, but the program still builds, and the run-time access is undefined behaviour.
Can the array index be a negative number?
Syntactically it compiles, but for a normal array any negative index goes before the first element and is invalid. Use unsigned types to avoid the mistake.
Can I use a float as an array index?
No. The index must be an integer type. Convert or round the value to an integer first.
What does arr[i++] do?
It uses the current value of i as the index and then increases i by one. It is legal, but separate statements are easier to read.
How do I catch array bound errors while testing?
Build your code on a PC with AddressSanitizer and UndefinedBehaviorSanitizer enabled. They stop the program at the exact line that accessed the invalid element.
Why is bounds checking left to the programmer in C?
C was designed for small, fast, close-to-hardware programs, so the language adds no hidden run-time checks. That keeps the code lean, and it is why embedded programmers must be disciplined.
Next in the Free C Programming Course
Next we combine arrays with loops to read, display and add up whole arrays, the foundation of every sensor-processing routine you will write.

1 Comment