C Arrays
An array is a collection of elements of the same type stored in contiguous memory. Each element is accessed using an index, starting at 0 for the first element.
Arrays have a fixed size determined at declaration time, and C does not automatically check whether an index is within bounds, so care is needed to avoid reading or writing outside the array.
type name[size] = {values};Declaring and initializing
You can declare an array with a fixed size like `int nums[5];`, or initialize it directly with values like `int nums[] = {1, 2, 3};`, letting the compiler infer the size.
Accessing elements
Elements are accessed with square-bracket indexing, such as `nums[0]` for the first element. Indexes range from 0 to size minus 1.
#include <stdio.h>
int main() {
int nums[3] = {10, 20, 30};
printf("%d\n", nums[1]);
return 0;
}20nums[1] accesses the second element (index starts at 0), which is 20.
#include <stdio.h>
int main() {
int nums[4] = {1, 2, 3, 4};
for (int i = 0; i < 4; i++) {
printf("%d ", nums[i]);
}
printf("\n");
return 0;
}1 2 3 4 A for loop is a common way to iterate through every element of an array.
Key points
- Array indexing starts at 0.
- All elements of an array share the same data type.
- C does not check array bounds automatically.
- Array size is fixed once declared (unless using dynamic memory).
