SyntaxStudy
Sign Up
C Arrays and Pointer Arithmetic
C Beginner 1 min read

Arrays and Pointer Arithmetic

An array in C is a contiguous block of memory holding a fixed number of elements of the same type. You declare an array as `type name[size]` and access elements with zero-based indexing: `arr[0]` through `arr[size-1]`. C does not perform bounds checking, so accessing an index outside the valid range causes undefined behaviour — one of the most dangerous classes of bugs in C programs. The name of an array, when used in most expressions, decays to a pointer to its first element. This means `arr` and `&arr[0]` are equivalent in most contexts. Pointer arithmetic lets you navigate an array using a pointer: adding `n` to a pointer advances it by `n` elements (not `n` bytes), because the compiler knows the element size. `ptr + 1` points to the next element, `ptr[n]` is syntactic sugar for `*(ptr + n)`. Multidimensional arrays in C are arrays of arrays, stored in row-major order. A 2D array `int mat[3][4]` stores three rows of four integers contiguously. When passing a 2D array to a function, you must specify all dimensions except the first: `void f(int mat[][4], int rows)`. Pointer arithmetic on multidimensional arrays follows the same rules but requires care with the element type.
Example
#include <stdio.h>

#define ROWS 3
#define COLS 4

void print_matrix(const int mat[][COLS], int rows)
{
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < COLS; c++)
            printf("%4d", mat[r][c]);
        printf("\n");
    }
}

int main(void)
{
    /* 1D array initialisation */
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);

    /* Index-based access */
    printf("arr[2] = %d\n", arr[2]);    /* 30 */

    /* Pointer arithmetic — equivalent ways to traverse */
    int *p = arr;
    for (int i = 0; i < n; i++)
        printf("%d ", *(p + i));        /* same as arr[i] */
    printf("\n");

    /* Pointer walking */
    for (int *q = arr; q < arr + n; q++)
        printf("%d ", *q);
    printf("\n");

    /* 2D array */
    int mat[ROWS][COLS] = {
        { 1,  2,  3,  4},
        { 5,  6,  7,  8},
        { 9, 10, 11, 12}
    };
    print_matrix(mat, ROWS);

    /* Flatten 2D to 1D pointer arithmetic */
    int *flat = &mat[0][0];
    printf("Element [1][2] via flat pointer: %d\n",
           flat[1 * COLS + 2]);          /* 7 */

    return 0;
}