C Programming Arrays Reference
Core Data Structure

C Arrays - Complete Guide

Master C arrays including 1D and 2D arrays with detailed syntax, practical examples, memory representation, and programming best practices.

1D & 2D Arrays

Complete coverage

Memory Representation

Visual understanding

Matrix Operations

Real-world applications

1. Introduction to Arrays

Overview of C arrays: 1D contiguous memory, indexing, and 2D row-major layout
C arrays: One-dimensional arrays as contiguous indexed elements, and two-dimensional arrays as rows and columns stored in row-major order.

1.1 What is an Array?

An array is a fundamental data structure in C that stores a fixed-size sequential collection of elements of the same data type. Think of a row of numbered boxes: each box holds one item, and all boxes are the same size and type.

Real-world analogies:

  • A parking lot with numbered spaces
  • A row of school lockers
  • An egg carton

1.2 Why Do We Need Arrays?

Without array vs with array
// Without array (inefficient)
int student1 = 85;
int student2 = 90;
int student3 = 78;
// What if you have 1000 students?

// With array (efficient)
int students[1000];
  • Code organization — group related data
  • Memory efficiency — contiguous allocation
  • Easy traversal — loops with an index
  • Readability — cleaner code
  • Algorithms — sort, search, statistics

1.3 Memory Representation

C allocates a contiguous block. Total bytes = elements × sizeof(type).

Example
int arr[5];  // 5 × 4 = 20 bytes (typical int)
Memory Address: 1000 1004 1008 1012 1016 ┌──────┬──────┬──────┬──────┬──────┐ Content: │ ? │ ? │ ? │ ? │ ? │ └──────┴──────┴──────┴──────┴──────┘ Index: 0 1 2 3 4

1.4 Array Properties

PropertyDescriptionExample
Fixed sizeSize fixed after declarationint arr[10];
HomogeneousSame element typeAll int or all float
Zero-basedFirst at index 0arr[0]
ContiguousConsecutive addresses+ sizeof(type) each step
Random accessDirect by indexarr[5] = 6th element

2. One-Dimensional Arrays (1D)

2.1 Detailed Declaration Syntax

Syntax:
data_type array_name[array_size];
ComponentDescriptionRules
data_typeElement typeint, float, char, …
array_nameIdentifierVariable naming rules
array_sizeElement countPositive integer constant
Valid
int scores[100];\nfloat temperatures[31];\nchar name[50];
Invalid
int arr[];           // Error: size required
int arr[-5];         // Error: negative size
int arr[10.5];       // Error: not integer
// int arr[n];       // VLA — C99 only

2.2 Comprehensive Initialization Methods

Method 1 — complete:

Complete
int arr[5] = {10, 20, 30, 40, 50};
Index: 0 1 2 3 4\nValue: 10 20 30 40 50

Method 2 — partial (rest are 0):

Partial
int arr[5] = {10, 20};  // 10, 20, 0, 0, 0

Method 3 — compiler sets size:

Size from list
int arr[] = {10, 20, 30, 40, 50};
char str[] = "Hello";  // size 6 with '\0'

Method 4 — all zeros:

Zero init
int arr[5] = {0};

Method 5 — designated (C99):

Designated
int arr[10] = {[2]=5, [5]=10, [8]=15};

Method 6 — loop:

Loop init
int arr[10];
for (int i = 0; i < 10; i++)
    arr[i] = i * 2;

2.3 Accessing Array Elements

Syntax: array_name[index]. Valid: 0size-1. Out of bounds = undefined behavior.

Access example
#include 
int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    printf("arr[0] = %d\n", arr[0]);
    int i = 3;
    printf("arr[%d] = %d\n", i, arr[i]);
    printf("arr[1+2] = %d\n", arr[1+2]);
    arr[2] = 99;
    return 0;
}

2.4 Array Traversal Patterns

Pattern 1 — forward:

Forward
int arr[5] = {1,2,3,4,5};
for (int i = 0; i < 5; i++)
    printf("%d ", arr[i]);

Pattern 2 — reverse:

Reverse
for (int i = 4; i >= 0; i--)
    printf("%d ", arr[i]);

Pattern 3 — skip indices:

Skip
for (int i = 0; i < 10; i += 2)
    arr[i] = i * 10;

Pattern 4 — two pointers:

Two pointers
int left = 0, right = 4;
while (left < right) {
    int temp = arr[left];
    arr[left] = arr[right];
    arr[right] = temp;
    left++; right--;
}

3. Two-Dimensional Arrays (2D)

3.1 Understanding 2D Arrays

A 2D array is an array of arrays — tabular data with rows and columns (chess board, theater seats, spreadsheet, image pixels).

int matrix[3][4]; Col0 Col1 Col2 Col3 Row0 → [0][0] [0][1] [0][2] [0][3] Row1 → [1][0] [1][1] [1][2] [1][3] Row2 → [2][0] [2][1] [2][2] [2][3] Total = 3 × 4 = 12 elements

3.2 Memory Layout (Row-Major Order)

All elements of row 0, then row 1, then row 2…

Example
int matrix[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
Address of arr[i][j] = Base + (i × columns + j) × sizeof(data_type)

3.3 Declaration and Initialization

Declarations
int matrix[3][4];
#define ROWS 3
#define COLS 4
int m[ROWS][COLS];
Row-wise
int m[2][3] = {{1,2,3}, {4,5,6}};
Linear
int m[2][3] = {1,2,3,4,5,6};
Partial
int m[3][4] = {{1,2}, {4,5,6}, {7}};
Omit rows
int m[][3] = {{1,2,3},{4,5,6},{7,8,9}};
Designated 2D
int matrix[3][3] = {[0][0]=1, [1][1]=5, [2][2]=9};

Applications of 2D Arrays

  • Matrix operations
  • Game boards
  • Tables and grade sheets
  • Image processing
  • Spreadsheet-style programs

Difference Between 1D and 2D Arrays

Feature1D Array2D Array
StructureSingle rowRows and columns
IndexOne indexTwo indexes
Examplearr[5]arr[3][3]
LoopsSingle loopNested loops
UsageLinear dataMatrix data

Common Mistakes and Best Practices

Common Mistake 1: Index Out of Bounds
int arr[5]; arr[5] = 10; // ERROR! Valid indices are 0-4 arr[-1] = 20; // ERROR! Negative index not allowed
Solution: Always check array bounds before accessing
Common Mistake 2: Uninitialized Arrays
int scores[100]; // Contains garbage values // Should initialize: int scores[100] = {0}; // All zeros
Common Mistake 3: Wrong Array Size
int n = 10; int arr[n]; // Variable-length array (C99+) // Better for fixed size: #define SIZE 10 int arr[SIZE];
Array Best Practices:
  1. Always initialize arrays before use
  2. Use symbolic constants for array sizes (#define)
  3. Validate array indices before access
  4. Pass array size as parameter when using functions
  5. Use sizeof() operator to calculate array size
  6. Choose appropriate array dimension (1D vs 2D)
  7. Document array purpose and structure
  8. Test with boundary cases (empty, single, full)

Key Takeaways

  • Arrays store homogeneous elements in contiguous memory
  • 1D arrays use single indexing; 2D arrays use row-column indexing
  • C uses zero-based indexing (first element at index 0)
  • 2D arrays are stored in row-major order in memory
  • Always specify array size (except with initialization)
  • Arrays are passed by reference to functions
  • Use loops for array traversal and operations
  • Watch for index out of bounds errors
  • Arrays have fixed size determined at compile time
  • Initialize arrays to avoid garbage values
Next Topics: We'll explore strings (character arrays) in detail, including string functions, manipulation, and common operations using arrays.