Arrays in C are collections of elements of the same data type, stored in contiguous memory locations. They are indexed starting from 0, and the subscript (index) used to access an array element can be an expression that evaluates to an integer.
Accessing Arrays and Bounds
It is important to note that accessing an array outside its declared bounds does not necessarily produce an error, but it leads to undefined behavior. This means that the program may read or write unintended memory locations, potentially causing crashes or unexpected results.
Example of an Array Declaration
If an array is declared as:
- The first element (
array[0]) is initialized to 10.
- All remaining elements (
array[1] to array[9]) are automatically initialized to 0.
Incorrect Declaration Example
A common mistake in character array initialization:
char alpha[3] = {a, b, c}; // Incorrect
Here, a, b, and c are not enclosed in single quotes, so the compiler will not recognize them as character literals.
Correct Declaration Example
To correctly initialize a character array, use single quotes for characters:
char alpha[3] = {'a', 'b', 'c'};
Alternatively, a string (null-terminated character array) can be declared as:
char alpha[] = "abc"; // Automatically allocates space for 'a', 'b', 'c', and '\0'
Array Indexing with Expressions
C allows the use of expressions as array indices. For example:
int numbers[5] = {10, 20, 30, 40, 50};
int index = 2;
printf("%d", numbers[index + 1]); // Output: 40
This flexibility allows dynamic indexing in programs.
Avoiding Out-of-Bounds Access
To prevent accessing elements outside the valid range, always ensure that indices are within the defined size of the array:
int arr[5] = {1, 2, 3, 4, 5};
int idx = 6; // Out of bounds
if (idx >= 0 && idx < 5) {
printf("%d", arr[idx]);
} else {
printf("Index out of bounds!\n");
}
Summary
- Arrays in C have zero-based indexing.
- Accessing an index outside the declared range results in undefined behavior.
- Partial initialization of an array fills the remaining elements with zeros (for static or global arrays).
- Character arrays should use single quotes for characters (
'a', 'b') and double quotes for strings ("abc").
- Always validate array indices to prevent unintended memory access.
Understanding these fundamentals helps in writing safe and efficient C programs.