ccompiler.inOnline C Compiler & Docs
C Tutorial2026-03-152 min read

Master 1D and 2D arrays in C. Learn memory layout, indexing, passing arrays to functions, boundary safety, and matrix operations with full code.

What is an Array in C?

An array is a fixed-size, contiguous collection of elements of the same data type stored sequentially in memory. In C, arrays provide index-based O(1) random access to elements.

Because array elements are stored in adjacent memory addresses, accessing arr[i] computes the memory offset as base_address + (i * sizeof(type)).

Declaring and Initializing 1D Arrays

c (ISO Standard)
#include <stdio.h>

int main() {
    int scores[5] = {88, 92, 79, 95, 85};
    int length = 5;

    printf("Array elements:\n");
    for (int i = 0; i < length; i++) {
        printf("Element at index [%d] = %d (Address: %p)\n", i, scores[i], (void*)&scores[i]);
    }

    return 0;
}

Two-Dimensional (2D) Arrays & Matrices

2D arrays represent grids or matrices stored in row-major order in contiguous memory:

c (ISO Standard)
#include <stdio.h>

int main() {
    int matrix[2][3] = {
        {10, 20, 30},
        {40, 50, 60}
    };

    printf("2D Array Grid:\n");
    for (int row = 0; row < 2; row++) {
        for (int col = 0; col < 3; col++) {
            printf("%d\t", matrix[row][col]);
        }
        printf("\n");
    }

    return 0;
}

Passing Arrays to Functions

When you pass an array to a function in C, it automatically decays into a pointer to its first element (int *arr or int arr[]). Therefore, you should always pass the array size as an additional argument:

c (ISO Standard)
#include <stdio.h>

int calculateSum(int arr[], int size) {
    int total = 0;
    for (int i = 0; i < size; i++) {
        total += arr[i];
    }
    return total;
}

int main() {
    int values[] = {5, 10, 15, 20};
    int total = calculateSum(values, 4);

    printf("Total sum: %d\n", total);
    return 0;
}

Array Safety Guidelines

  1. No Bounds Checking: C does not perform automatic runtime boundary checking. Accessing arr[10] in an array of size 5 results in undefined behavior or memory corruption.
  2. Buffer Overflows: Always ensure iteration indices strictly satisfy 0 <= index < size.

Related Tutorials & Examples