Arrays & Strings

Master contiguous memory blocks, 2D matrices, array decay to pointers, string handling, and avoid buffer overflows.

1D Arrays

A collection of elements of the same data type stored in contiguous memory.

array1d.c
#include <stdio.h> int main() { // Declare array of 5 integers int scores[5]; // Initialize elements scores[0] = 85; scores[1] = 92; scores[4] = 95; // Loop through array for (int i = 0; i < 5; i++) { printf("Index %d: %d\n", i, scores[i]); } return 0; }
Memory Layout (4 bytes per int): Index Value Address ─────────────────────────── 0 85 1000 ┐ 1 92 1004 │ Contiguous 2 ?? 1008 │ Memory Block 3 ?? 1012 │ 4 95 1016 ┘

Declaration Styles

int arr1[10]; // Uninitialized int arr2[] = {1, 2, 3}; // Size 3 int arr3[5] = {1, 2}; // [1, 2, 0, 0, 0]

Key Rules

  • Size is constant at compile time
  • Indices: 0 to (size-1)
  • No bounds checking!
  • Name is pointer to first element

2D Arrays

Matrices and tables. Arrays of arrays.

matrix.c
int matrix[2][3] = { {1, 2, 3}, // Row 0 {4, 5, 6} // Row 1 }; // Access: matrix[row][col] printf("%d", matrix[1][2]); // Output: 6

Memory Layout

How multi-dimensional arrays are flattened in RAM.

2D Array: int mat[2][2] = {{1,2}, {3,4}}; Logical View: Physical RAM (Row-Major Order): ┌───┬───┐ ┌───┬───┬───┬───┐ │ 1 │ 2 │ │ 1 │ 2 │ 3 │ 4 │ ├───┼───┤ └───┴───┴───┴───┘ │ 3 │ 4 │ [0][0] [0][1] [1][0] [1][1] └───┴───┘ Address increases linearly ----->
Row-Major Order: C stores arrays row by row. This is crucial for cache performance. Always loop through rows first, then columns.

Array Decay

The concept of arrays "decaying" into pointers when passed to functions.

decay.c
void printSize(int arr[]) { // Decays to (int *), size is 8 bytes (pointer) printf("%lu", sizeof(arr)); } int main() { int nums[10]; // True size: 10 * 4 = 40 bytes printf("%lu", sizeof(nums)); printSize(nums); }

Strings

Character arrays terminated by a null character '\0'.

Declaration

char s1[] = "Hello"; // Size is 6 ('H','e','l','l','o','\0') char s2[10] = "Hi"; // s2[2] through s2[9] are 0

String Functions

  • strlen(): Length excluding \0
  • strcpy(): Copy string (Unsafe)
  • strcat(): Concatenate
  • strcmp(): Compare
String: "C" Index: 0 1 Char: 'C' '\0' ASCII: 67 0