An array is a fixed-size, sequential collection of elements of the same data type, stored in contiguous (adjacent) memory locations. Arrays are fundamental for processing lists, tables, and sequences of data in C.
1. Declaring and Initializing Arrays
A. Declaration
To declare an array, you must specify the data type and the size (the number of elements) inside square brackets ([]).
Syntax: dataType arrayName[size];
int scores[5]; // An array of 5 integers
char name[20]; // An array of 20 characters
B. Initialization
You can initialize an array during declaration by enclosing the values in curly braces ({}).
int numbers[3] = {10, 20, 30};
C. Size Deduction (Implicit Sizing)
If you initialize an array during declaration, you can omit the size. The compiler will automatically calculate the size based on the number of initializers provided.
// The size is automatically set to 4
float prices[] = {9.99f, 5.49f, 12.00f, 1.50f};
2. Accessing Array Elements
Array elements are accessed using their index (or subscript), which specifies their position in the collection.
- Crucial Rule: C arrays are zero-indexed. The first element is at index
0, and the last element is at indexsize - 1.
Reading and Writing Elements
To access or change a value, use the array name followed by the index in brackets:
int grades[4] = {85, 92, 78, 95};
// Reading the first element (index 0)
int first_grade = grades[0]; // first_grade is 85
// Writing to the third element (index 2)
grades[2] = 80;
// The last element is at index 3
printf("The last grade is: %d\n", grades[3]);
3. Iterating Through Arrays
The for loop is the standard and most robust way to process every element in an array.
Example: Calculating the Sum
int data[] = {1, 5, 2, 8, 3};
int sum = 0;
int i;
// Calculate the number of elements using sizeof operator
int size = sizeof(data) / sizeof(data[0]);
for (i = 0; i < size; i++) {
sum += data[i];
}
printf("Total sum: %d\n", sum);
4. Arrays and Memory
Because array elements are stored contiguously in memory, the name of the array (e.g., scores) acts as a constant pointer to the memory address of the first element (scores[0]). This relationship is the core of C and will be detailed further in the next chapter.
5. Multi-dimensional Arrays (2D Arrays)
C supports arrays of arrays, commonly used to represent tables or matrices. The most common is a two-dimensional array, defined by specifying both rows and columns.
Syntax: dataType arrayName[rows][columns];
// A 2x3 matrix (2 rows, 3 columns)
int matrix[2][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6} // Row 1
};
// Accessing the element in the second row (index 1), third column (index 2)
int element = matrix[1][2]; // element is 6
