An Array is a fixed-size, sequenced collection of elements of the same data type. It is used to store multiple values in a single variable, rather than declaring separate variables for each value.
Key Concept: Arrays are used when we need to handle a large amount of related data of the same type (e.g., marks of 50 students).
To declare an array in C, you specify the data type of the elements and the number of elements required by the array.
data_type array_name[array_size];
Example: int marks[5];
This tells the compiler to reserve space for 5 integers under the name 'marks'.
Initialization refers to assigning values to the array elements at the time of declaration.
int age[5] = {20, 22, 19, 21, 23};int num[5] = {10, 20}; (Remaining elements 2, 3, and 4 are automatically set to 0).int score[] = {10, 20, 30}; (Compiler automatically sets the size to 3).Array elements are accessed using an index (also called a subscript). In C, array indexing always starts from 0 and ends at size - 1.
int marks[3] = {85, 90, 78};
printf("%d", marks[0]); // Output: 85
printf("%d", marks[2]); // Output: 78
Since arrays occupy contiguous memory, the address of any element can be calculated if the base address (address of the first element) is known.
Formula for address calculation:
Address of A[i] = Base Address + (i * size_of_data_type)
Example: If an integer array starts at address 1000 and each integer takes 4 bytes, then marks[2] would be at:
1000 + (2 * 4) = 1008.
A 2D array is essentially an "array of arrays." It is commonly used to represent tables or matrices.
data_type array_name[rows][columns];
Example: int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
This creates a table with 2 rows and 3 columns.
Common operations performed on arrays include:
for loop).array[0], not array[1].i < N or i <= N-1.marks[5] in an array of size 5. C does not check for boundary errors; it will simply access "garbage" memory, which can crash your program.float in an int array. This will lead to data loss (truncation).int a[]; without immediate initialization. The compiler must know the size to allocate memory.Q: Why is it called a "Static" data structure?
A: Because the size of the array is fixed at compile-time and cannot be changed during the execution of the program.
Q: What is the base address?
A: The base address is the memory location of the very first element (index 0) of the array.