Unit 7: Arrays
Contents
1. Declaring Arrays in C
An array is a data structure that can store a fixed-size sequential collection of elements of the same type. Declaring an array tells the compiler about the type of elements and the number of elements it will hold.
Syntax:
data_type array_name[array_size];
Example: int marks[5]; reserves space for 5 integer values.
2. Defining and Processing 1-Dimensional Arrays
A 1-dimensional array is the simplest form of an array where elements are stored linearly. Defining an array involves assigning initial values.
Initialization:
int numbers[5] = {10, 20, 30, 40, 50};Processing:
Processing usually involves traversing the array using a loop to perform operations like reading, printing, or calculating sums.
for(int i = 0; i < 5; i++) { printf("%d ", numbers[i]); } 3. Defining and Processing 2-Dimensional Arrays
A 2-dimensional array is essentially an array of arrays, often visualized as a table with rows and columns.
Declaration and Initialization:
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };Processing:
Processing 2D arrays requires nested loops—the outer loop for rows and the inner loop for columns.
for(int i = 0; i < 2; i++) { for(int j = 0; j < 3; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } 4. Passing Array as an Argument to Function
In C, you can pass an entire array to a function as a parameter. However, it is important to note that arrays are passed by reference (the address of the first element is passed).
Syntax in Function Definition:
void display(int arr[], int size) { ... }Calling the Function:
display(marks, 5);
Changes made to the array inside the function will affect the original array in the calling function.
5. Multi-dimensional Arrays
C supports arrays with more than two dimensions. While 3D or higher arrays are possible, they are less common and more complex to manage in memory.
Example (3D Array):
int survey[2][3][4];
This can be thought of as 2 blocks, each containing a 3x4 matrix.
6. Exam Focus Enhancements
- Index Start: Always remember that array indices start at 0 and end at size - 1.
- Memory Calculation: Total size of an array = array_size * sizeof(data_type).
- 2D Arrays: When declaring a 2D array as a function parameter, the column size must be specified (e.g.,
void func(int arr[][3])).
- Out of Bounds: Accessing
arr[5]in an array of size 5. This leads to garbage values or crashes. - Initialization: Forgetting that partial initialization (e.g.,
int a[5] = {1, 2};) fills the remaining spots with zero. - Pointer Confusion: Passing
&arrto a function instead of justarrwhen the function expects an array pointer.
Q: Why are arrays passed by reference by default?
A: To save memory and time. Copying a large array would be inefficient.
Q: Can the size of an array be changed at runtime?
A: No, standard C arrays have a static size fixed at declaration. Dynamic allocation (malloc) is needed for flexible sizes.