01. 1D Arrays & Contiguous Memory Layout in C

🟢 Difficulty: Beginner | Sequential RAM Layout, Zero-Based Indexing & Address Offsets

📖 Definition

A 1D array in C is a contiguous block of memory allocated to hold a fixed number of elements of the same data type. Elements are indexed starting from zero (0) up to N - 1, where N is the declared length of the array.

🎯 Why It Is Used

  • O(1) Direct Memory Indexing: Accessing any element by index requires constant time $O(1)$ because the memory address is computed via direct offset addition: Address(arr[i]) = BaseAddress + (i * sizeof(ElementType)).
  • CPU Cache Locality: Contiguous memory placement maximizes hardware prefetching and L1/L2 cache hit ratios during sequential loops.

⚙️ How It Works: Address Offset Math

If an integer array int arr[5] starts at memory address 0x1000 and sizeof(int) == 4 bytes:

  • arr[0] address = 0x1000
  • arr[1] address = 0x1000 + (1 * 4) = 0x1004
  • arr[2] address = 0x1000 + (2 * 4) = 0x1008
  • arr[i] address = BaseAddress + (i * sizeof(ElementType))

📝 Syntax

// 1. Declaration without initialization (Contains garbage data if local!)
int scores[10];

// 2. Declaration with explicit initializer list
int primes[5] = {2, 3, 5, 7, 11};

// 3. Zero-filling all elements
int buffer[100] = {0}; // All 100 elements zero-initialized!

// 4. C99 Designated Initializers
int sparse[5] = {[0] = 10, [3] = 40}; // indices 1, 2, 4 are automatically 0

🔀 Calculating Array Length At Compile Time

In C, arrays do not store their length at runtime. To compute the element count of a static stack array, divide the total array size in bytes by the size of a single element:

int data[] = {10, 20, 30, 40, 50};
size_t length = sizeof(data) / sizeof(data[0]); // Computes 20 / 4 = 5

🌱 Beginner Example

#include <stdio.h>

int main(void) {
    int marks[5] = {85, 92, 78, 90, 88};
    size_t count = sizeof(marks) / sizeof(marks[0]);

    printf("=== Student Test Marks ===\n");
    for (size_t i = 0; i < count; i++) {
        printf("Student #%zu: %d\n", i + 1, marks[i]);
    }
    return 0;
}

🌼 Intermediate Example: Inspecting RAM Address Offsets

#include <stdio.h>

int main(void) {
    int numbers[4] = {100, 200, 300, 400};

    printf("=== Contiguous RAM Address Breakdown ===\n");
    printf("Base Array Pointer Address (&numbers): %p\n", (void*)numbers);

    for (int i = 0; i < 4; i++) {
        printf("Element numbers[%d] | Address: %p | Value: %d\n",
               i, (void*)&numbers[i], numbers[i]);
    }
    return 0;
}

🌲 Advanced Example: Reversing an Array In-Place

#include <stdio.h>

void reverse_array_in_place(int arr[], size_t size) {
    if (arr == NULL || size == 0) return;

    size_t left = 0;
    size_t right = size - 1;

    while (left < right) {
        // Swap elements at left and right pointers
        int temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;

        left++;
        right--;
    }
}

int main(void) {
    int values[] = {1, 2, 3, 4, 5, 6};
    size_t len = sizeof(values) / sizeof(values[0]);

    reverse_array_in_place(values, len);

    printf("Reversed Array: ");
    for (size_t i = 0; i < len; i++) {
        printf("%d ", values[i]);
    }
    printf("\n");
    return 0;
}

🔍 Line-by-Line Explanation

  • int buffer[100] = {0};: Zero-initializes all 100 elements. Specifying the first element as 0 causes C to fill all remaining unlisted elements with zeroes.
  • (void*)&numbers[i]: Prints hexadecimal RAM addresses for each element, demonstrating 4-byte address spacing for int.
  • sizeof(values) / sizeof(values[0]): Idiomatic idiom for calculating total elements in a fixed array.

💻 Expected Terminal Output

=== Student Test Marks ===
Student #1: 85
Student #2: 92
Student #3: 78
Student #4: 90
Student #5: 88
=== Contiguous RAM Address Breakdown ===
Base Array Pointer Address (&numbers): 0x7ffd8a12b400
Element numbers[0] | Address: 0x7ffd8a12b400 | Value: 100
Element numbers[1] | Address: 0x7ffd8a12b404 | Value: 200
Element numbers[2] | Address: 0x7ffd8a12b408 | Value: 300
Element numbers[3] | Address: 0x7ffd8a12b40c | Value: 400
Reversed Array: 6 5 4 3 2 1 

⚠️ Common Mistakes & Pitfalls

  • Out-of-Bounds Index Access: Accessing arr[5] on an array declared as int arr[5] (valid indices are 0 through 4) triggers Undefined Behavior or Buffer Overflow.
  • Uninitialized Local Array Garbage: Declaring int arr[10]; inside a function without initializers leaves random memory garbage in the array.
  • Attempting Array Re-assignment: In C, array names are constant non-modifiable lvalues (e.g. arr1 = arr2; is illegal in C; use memcpy() or loop copy).

📌 Important Rules & Limitations

  • Array index bounds are NOT checked at compile time or runtime in C.
  • Static and global arrays are automatically zero-initialized by the C runtime environment.

🌐 Multilingual Explanation: English

A 1D array stores elements sequentially in contiguous RAM. Accessing elements by zero-based index takes constant O(1) time using memory address offsets.

🌐 Multilingual Explanation: Hindi (Roman Script)

1D array RAM mein saare elements ko continuously ek ke baad ek store karta hai. Array ka pehla index 0 hota hai aur aakhri index N-1.

🌐 Multilingual Explanation: Marathi (Roman Script)

1D array RAM madhye elements satat (contiguous) store karto. Index 0 pasun suru hoto.

❓ Practice Questions

  1. Why does accessing an element by index in a C array take $O(1)$ time?
  2. What is the difference in initialization between int a[10]; inside a function versus at global scope?
  3. How do you zero-initialize all elements of an array in C?

🚀 Practical Coding Challenge

Write a C program named second_largest.c that initializes an array of 8 integers, iterates through it in a single pass, and finds both the largest and second-largest elements.

🧭 Navigation & Breadcrumbs

← Module 09 Guide | Next: 02. 2D & Multidimensional Matrices →