6.1 One-Dimensional Arrays
An array is a fixed-size, contiguous block of memory holding elements of the same type, accessed by a zero-based index: arr[0] is the first element. Because the memory is contiguous, the address of arr[i] can be computed directly as base_address + i * sizeof(type), which is why array access is O(1).
int arr[5] = {10, 20, 30, 40, 50};
Elements are stored in contiguous memory; each int occupies 4 bytes, so consecutive addresses differ by 4 (0x100, 0x104, 0x108 ...).
Array Insertion Shifting Mechanics
In C, inserting an element at index k requires physically moving subsequent elements right to prevent overwriting existing data. Deletion performs the reverse left shift — both require O(n) operations:
// Shift right to insert 99 at index 2
for (int i = n; i > 2; i--) {
arr[i] = arr[i - 1];
}
arr[2] = 99;
6.2 Multidimensional Arrays
A 2D array (int m[rows][cols]) models a grid/table. C stores it in row-major order — the entire first row is laid out in memory, followed by the entire second row, and so on. This layout matters for cache performance: looping over columns within a row (the innermost dimension) is faster than the reverse.
int m[2][3] = {{1,2,3},{4,5,6}}; // (row-major storage)
C stores 2D arrays row by row: row 0 fully, then row 1.
Address of m[i][j] = base + (i*cols + j) * sizeof(int)
6.3 Arrays and Functions
When an array is passed to a function, C does not copy it — it decays into a pointer to its first element. This means the function receives the array's address directly, so any modification inside the function affects the original array. Because size information is lost in this decay, the array's length must be passed as a separate parameter.
void modify(int arr[], int n) {
for (int i = 0; i < n; i++) arr[i] *= 2; // affects caller's array
}
Why sizeof() fails inside functions:
- In the caller scope where
int arr[10];is defined,sizeof(arr)evaluates to40bytes (10 elements × 4 bytes). - Once passed into
modify(int arr[], int n), the compiler treatsarras a pointer (int *arr). Therefore,sizeof(arr)inside the function returns8bytes (the size of a 64-bit pointer), not 40! - Always pass array length
nexplicitly as a separate parameter in C APIs.