4) Arrays in C
Table of Contents
Arrays
Arrays are fundamental data structures in C that allow you to store a collection of elements of the same data type in a contiguous block of memory.
Each element in an array is accessed using an index, which represents its position within the array.
Arrays provide an efficient way to manage and manipulate collections of data.
Declaring and Initializing Arrays
Arrays are declared using the syntax: data_type array_name[array_size];
You can initialize arrays during declaration or later using loops or individual assignments.
Example: Declaring and Initializing an Array of Integers
#include <stdio.h>
int main() {
// Declaring and initializing an array of integers
int numbers[5] = {2, 4, 6, 8, 10};
// Accessing array elements using index
printf("Third element: %d\n", numbers[2]); // 6
return 0;
}
Explanation:
- In this example, an array named
numbers
of size 5 is declared and initialized with integer values. - The array indices start from 0, so
numbers[2]
accesses the third element in the array, which is 6.
Accessing Array Elements
Array elements are accessed using their indices within square brackets array_name[index]
.
Example: Accessing Array Elements Using Loop:
#include <stdio.h>
int main() {
int marks[5] = {85, 92, 78, 95, 88};
printf("Marks: ");
for (int i = 0; i < 5; i++) {
printf("%d ", marks[i]);
}
printf("\n");
return 0;
}
Explanation:
- In this example, an array named
marks
is declared and initialized with exam scores. - A
for
loop is used to iterate through the array and print each element.
Array Size and Bounds:
Arrays have a fixed size defined during declaration. Attempting to access elements outside the array bounds can lead to undefined behavior, including program crashes or incorrect results.
Example: Array Bounds Violation
#include <stdio.h>
int main() {
int numbers[3] = {10, 20, 30};
printf("%d\n", numbers[5]); // Accessing out of bounds, result is unpredictable
return 0;
}
We find the size of an array using the sizeof operator. The sizeof
operator returns the size in bytes of its operand, which can be a data type, a variable, or an expression. When used with an array, it returns the total size occupied by the array in memory.
Here’s how you can use the sizeof
operator to find the size of an array:
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
// Calculate the number of elements in the array
int numElements = sizeof(numbers) / sizeof(numbers[0]);
printf("Size of the array: %lu bytes\n", sizeof(numbers)); // Total size in bytes
printf("Number of elements in the array: %d\n", numElements);
return 0;
}
Explanation:
- In this example, an integer array named
numbers
is declared and initialized. - The
sizeof(numbers)
gives the total size of the array in bytes. - The
sizeof(numbers[0])
gives the size of a single element (an integer) in bytes. - By dividing the total size by the size of a single element, you get the number of elements in the array.
Keep in mind that the sizeof
operator returns the size in bytes, so to get the number of elements, you need to divide the total size by the size of a single element.
Arrays as Function Parameters
Arrays can be passed to functions as parameters. However, in C, when you pass an array to a function, you’re actually passing a pointer to the array’s first element.
Example: Passing an Array to a Function
#include <stdio.h>
// Function to calculate the sum of an array
int calculateSum(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
int main() {
int values[] = {5, 10, 15, 20, 25};
int sum = calculateSum(values, 5);
printf("Sum of array elements: %d\n", sum);
return 0;
}
Important Considerations for Arrays in C
- Zero-based Indexing: Array indices start from 0, so the first element is accessed with index 0, the second with index 1, and so on.
- Array Size: Arrays have a fixed size, which must be known at compile time.
- Memory Allocation: Arrays are allocated in memory as contiguous blocks, ensuring efficient memory access.
- Initialization: Uninitialized array elements are set to default values (0 for integers, NULL for pointers, etc.).