ALGORITHMS
Course: Bachelor of Science / Engineering in Computer Science | Module 04:
Comprehensive Summary & Reference Sheet
1. One-Dimensional Arrays & Contiguous Memory Layout
An array is a fixed-size, homogeneous collection of elements stored in contiguous
virtual memory locations. Contiguous allocation guarantees O(1) constant-time
random access via index arithmetic.
Declaration: int arr[5] = {10, 20, 30, 40, 50}; (sizeof(int) = 4 bytes)
Index: [0] [1] [2] [3] [4]
Values: ±-------+ ±-------+ ±-------+ ±-------+ ±-------+
| 10 | | 20 | | 30 | | 40 | | 50 |
±-------+ ±-------+ ±-------+ ±-------+ ±-------+
RAM Address: 0x1000 0x1004 0x1008 0x100C 0x1010
^
Base Address (arr == &arr[0])
1.1 Effective Address Calculation & Array Decay
1D Address Formula:
Address(A[i]) = Base_Address + (i × sizeof(element_type))
Array-to-Pointer Decay: In almost all expressions (including function calls), an array
identifier arr implicitly decays into a pointer to its first element ( &arr[0] ). Exceptions:
sizeof(arr) and &arr .
Equivalence Identity: The subscript expression arr[i] is defined by the C standard as
syntactic sugar for pointer dereferencing: *(arr + i) .
Initialization Pattern
C Syntax
Resulting Memory State
Full Initialization
int a[4] = {1, 2, 3, 4};
{1, 2, 3, 4} (16 bytes)
Partial Initialization
int a[4] = {1, 2};
{1, 2, 0, 0} (unlisted elements zero-filled)
Zero Initialization
, int a[4] = {0};
{0, 0, 0, 0} (all elements set to zero)
Size-Inferred
int a[] = {5, 6, 7};
Compiler allocates exact length 3 (12 bytes)
Uninitialized Automatic
int a[4];
Indeterminate garbage values
2. Multi-Dimensional Arrays & Row-Major Mapping
C stores two-dimensional matrices M[R][C] linearly in physical RAM using Row-Major
Order (all elements of Row 0 are stored contiguously, followed by Row 1, etc.).
2.1 Address Translation Formulas (0-Based Indexing)
Let B denote the Base Address, W denote element byte width, R denote total rows, and
C denote total columns:
Row-Major Order (Standard in C / C++ / Python):
Address(M [i][j]) = B + W × [(i × C) + j]
Column-Major Order (Fortran / MATLAB):
Address(M [i][j]) = B + W × [(j × R) + i]
Function Parameter Rule: When passing a 2D array to a function ( void process(int
mat[][4], int rows) ), the first dimension (rows) may be omitted, but all subsequent
dimensions (columns) must be specified so the compiler can compute the row stride
$(i \times C)$.
3. Null-Terminated C Strings & <string.h> Reference
In C, a string is a 1D array of char terminated by the Null Terminator ( ‘\0’ , ASCII 0 ).
Storing a string of N visible characters requires at least N + 1 bytes of memory.
char str[] = “CODE”;
Index: [0] [1] [2] [3] [4]
Content: | ‘C’ | | ‘O’ | | ‘D’ | | ‘E’ | | ‘\0’ | -> strlen(str) = 4, sizeof(str) = 5
Function Signature
Operational Behavior
Time Complexity
size_t strlen(const char *s)
Counts characters preceding ‘\0’ (excludes null byte)
O(n)