Part 3 — Chapter 11

Chapter 11: Arrays

Sometimes a program needs to store multiple values of the same data type. Creating separate variables for each value becomes difficult to manage and inefficient. In C, arrays are used to store multiple values using a single variable name.

An array stores elements in contiguous memory locations, and each element can be accessed using a zero-based index.

1. What is an Array?

An array is a collection of elements of the same data type stored sequentially in memory. Each element in the array is identified using an index value.

Array Syntax

Syntax
C
data_type array_name[size];

Example

int marks[5]; // Creates an integer array capable of storing 5 values
2. Array Initialization & Access

Arrays can be initialized during declaration by enclosing values inside curly braces. These values are stored at contiguous indices starting from 0.

Declaration & Initialization

int numbers[5] = {10, 20, 30, 40, 50};

Memory Representation

Contiguous RAM Allocation (4 Bytes per Integer element)
index [0]
10
0x2000
index [1]
20
0x2004
index [2]
30
0x2008
index [3]
40
0x200C
index [4]
50
0x2010
Example Program
array_demo.c
C
#include <stdio.h>
 
int main()
{
    int numbers[5] = {10, 20, 30, 40, 50};
    int i;
 
    for(i = 0; i < 5; i++)
    {
        printf("%d\n", numbers[i]); // Access element using index i
    }
 
    return 0;
}

How It Works

The array stores multiple integer values in consecutive memory locations. The loop accesses each element using its index value. Array indexing starts from 0:
numbers[0] → first element (10)
numbers[1] → second element (20)
numbers[4] → last element (50)
The loop continues until all elements are accessed sequentially.

Console Output
10
20
30
40
50

Important Points

Keep these critical rules in mind when programming with arrays in C:

  • Uniform Data Type: All elements must have the same data type (homogeneous collection).
  • Fixed Size: The size of the array is fixed at compile-time and cannot be changed dynamically.
  • Contiguous Memory: Elements occupy sequential slots in memory with no gaps.
  • No Bounds Checking: C does not check array limits. Accessing invalid indices (e.g., numbers[10] for size 5) leads to **undefined behavior**.

Embedded Focus

In memory-constrained embedded systems, arrays are incredibly powerful because they store data sequentially in RAM. This provides extremely fast, fixed-time (O(1)) access speeds, which is crucial for real-time sensor logging and signal processing buffers.

sensor_buffer.c
C
int sensor_data[10]; // Ring buffer storing the last 10 ADC readings

In hardware driver design, arrays are commonly used as communication buffers (UART/SPI/I2C packets), hardware registers offsets lookup tables, and audio/signal processing filters.

← Chapter 10: Functions Chapter 12: Strings →