C Program to Access Array Elements Using Pointers

C Program to Access Array Elements Using Pointers

Arrays are one of the most important data structures in C. They allow you to store multiple values of the same type in contiguous memory locations. While array elements are usually accessed using indices, pointers provide an alternative that is more flexible and can be used for advanced memory operations.

Using pointers to access array elements helps you understand memory layout, pointer arithmetic, and how C treats arrays internally. In this tutorial, we will explore multiple methods to access array elements using pointers.

Understanding the Problem

Given an array of integers, the task is to access and print each element using pointers instead of traditional array indexing.

In C, the name of an array is equivalent to a pointer to its first element. By applying pointer arithmetic, we can efficiently traverse the array and manipulate its elements. This technique is especially useful when passing arrays to functions or performing complex operations in memory.

Accessing Array Elements Using Pointer Arithmetic

In this example, we use a pointer initialized to the first element of the array and use pointer arithmetic to access subsequent elements. This method avoids using array indices directly.

#include <stdio.h>

int main() {

    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr;
    int i;

    ptr = arr; // Pointer points to the first element of the array

    printf("Array elements are:\n");

    for (i = 0; i < 5; i++) {
        printf("%d ", *(ptr + i)); // Access elements using pointer arithmetic
    }

    printf("\n");

    return 0;

}

Here, *(ptr + i) dereferences the pointer after moving i positions forward, allowing us to read each element in the array.

Accessing Array Elements Using Pointer Increment

Another way to traverse an array is by incrementing the pointer itself. This method is concise and highlights how pointers move through memory locations.

#include <stdio.h>

int main() {

    int arr[5] = {100, 200, 300, 400, 500};
    int *ptr = arr; // Initialize pointer to first element
    int i = 0;

    printf("Array elements using pointer increment:\n");

    while (i < 5) {

        printf("%d ", *ptr); // Access current element
        ptr++; // Move pointer to the next element
        i++;

    }

    printf("\n");

    return 0;

}

Pointer increment automatically moves the pointer by the size of the data type, so each step accesses the next array element efficiently.

Accessing Array Elements in a Function

You can pass pointers to functions to manipulate or print array elements outside the main function. This approach is useful for modular code and demonstrates that arrays decay to pointers when passed to functions.

#include <stdio.h>

void printArray(int *ptr, int size) {

    printf("Array elements inside function:\n");

    for (int i = 0; i < size; i++) {
        printf("%d ", *(ptr + i)); // Access each element using pointer arithmetic
    }

    printf("\n");

}

int main() {

    int arr[5] = {7, 14, 21, 28, 35};

    printArray(arr, 5); // Pass array to function as a pointer

    return 0;

}

This method emphasizes modularity and shows how pointer arithmetic works in functions as well as in the main program.

Accessing Elements in a 2D Array Using Pointer Arithmetic

You can access elements of a 2D array by treating it as a contiguous block of memory and using pointer arithmetic.

#include <stdio.h>

int main() {

    int arr[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    int *ptr = &arr[0][0]; // Pointer to the first element

    printf("2D array elements using pointer arithmetic:\n");

    for (int i = 0; i < 3 * 3; i++) {
        printf("%d ", *(ptr + i));
    }

    printf("\n");

    return 0;

}

Here, *(ptr + i) moves linearly through all elements in row-major order.

Accessing 2D Array Elements Using Array Notation with Pointers

You can also use a pointer to the first row and access elements using *(ptr + row * cols + col) notation.

#include <stdio.h>

int main() {

    int arr[2][4] = {
        {10, 20, 30, 40},
        {50, 60, 70, 80}
    };

    int *ptr = &arr[0][0]; // Pointer to first element
    int rows = 2, cols = 4;

    printf("2D array elements with row/column calculation:\n");

    for (int i = 0; i < rows; i++) {

        for (int j = 0; j < cols; j++) {
            printf("%d ", *(ptr + i * cols + j));
        }

        printf("\n");

    }

    return 0;

}

This method shows how 2D arrays are stored linearly in memory and how to calculate positions manually.

Passing a 2D Array to a Function

You can pass a multi-dimensional array to a function either by specifying the number of columns or by using a pointer to the first element.

#include <stdio.h>

void print2DArray(int *arr, int rows, int cols) {

    printf("2D array elements in function:\n");

    for (int i = 0; i < rows; i++) {

        for (int j = 0; j < cols; j++) {
            printf("%d ", *(arr + i * cols + j));
        }

        printf("\n");

    }

}

int main() {

    int arr[2][3] = {
        {5, 10, 15},
        {20, 25, 30}
    };

    print2DArray(&arr[0][0], 2, 3);

    return 0;

}

This emphasizes modularity and shows that multi-dimensional arrays decay to pointers when passed to functions.

Accessing Elements in a 3D Array Using Pointer Arithmetic

A 3D array is stored in contiguous memory in row-major order, so we can access elements with pointer arithmetic.

#include <stdio.h>

int main() {

    int arr[2][2][3] = {
        {
            {1, 2, 3},
            {4, 5, 6}
        },
        {
            {7, 8, 9},
            {10, 11, 12}
        }
    };

    int *ptr = &arr[0][0][0]; // Pointer to first element

    printf("3D array elements using pointer arithmetic:\n");

    for (int i = 0; i < 2 * 2 * 3; i++) {
        printf("%d ", *(ptr + i));
    }

    printf("\n");

    return 0;

}

Here, *(ptr + i) moves linearly through the entire 3D array in memory.

Passing a 3D Array to a Function

You can pass a 3D array to a function by specifying the dimensions except the first.

#include <stdio.h>

void print3DArray(int arr[2][2][3]) {

    printf("3D array elements in function:\n");

    for (int i = 0; i < 2; i++) {

        for (int j = 0; j < 2; j++) {

            for (int k = 0; k < 3; k++) {
                printf("%d ", arr[i][j][k]);
            }

            printf("\n");

        }

        printf("\n");

    }

}

int main() {

    int arr[2][2][3] = {
        {
            {1, 2, 3},
            {4, 5, 6}
        },
        {
            {7, 8, 9},
            {10, 11, 12}
        }
    };

    print3DArray(arr);

    return 0;

}

This demonstrates modular access while keeping the array structure intact.

Dynamic 2D Arrays Using Pointers

Sometimes the array size is not known at compile-time. We can allocate a dynamic 2D array using pointers and malloc.

#include <stdio.h>
#include <stdlib.h>

int main() {

    int rows = 3, cols = 4;
    int **arr;

    // Allocate memory for row pointers
    arr = (int **)malloc(rows * sizeof(int *));

    for (int i = 0; i < rows; i++) {

        arr[i] = (int *)malloc(cols * sizeof(int));

    }

    // Initialize array
    for (int i = 0; i < rows; i++) {

        for (int j = 0; j < cols; j++) {
            arr[i][j] = i * cols + j + 1;
        }

    }

    // Print array
    printf("Dynamic 2D array elements:\n");

    for (int i = 0; i < rows; i++) {

        for (int j = 0; j < cols; j++) {
            printf("%d ", arr[i][j]);
        }

        printf("\n");

    }

    // Free memory
    for (int i = 0; i < rows; i++) {
        free(arr[i]);
    }

    free(arr);

    return 0;

}

This method is flexible and allows arrays to be sized at runtime, useful for large or unknown data sets.

FAQs

Answering common questions about accessing array elements with pointers in C.

1. Can this method work for multi-dimensional arrays?
Yes. Pointer arithmetic works for multi-dimensional arrays, but you need to account for row and column sizes. For dynamic arrays, pointers to pointers (int **) are often used.

2. Is pointer access faster than array indexing?
Modern compilers typically optimize both methods similarly. Pointers are more useful for dynamic memory and complex operations like traversing multi-dimensional arrays efficiently.

3. Can I modify array elements using pointers?
Yes. You can assign new values with *(ptr + i) = value; or increment the pointer and modify the dereferenced value directly.

4. What happens if I increment a pointer beyond the array?
Doing so leads to undefined behavior. It may crash the program or produce unexpected results. Always ensure pointer operations stay within the array bounds.

5. When should I use pointers instead of array indices?
Use pointers when working with dynamic memory, functions, or complex data structures. For simple loops, array indexing is usually clearer and easier to read.

Conclusion

Accessing array elements using pointers is a fundamental concept in C programming. It gives insight into memory layout and allows flexible, efficient manipulation of arrays.

We explored multiple techniques: pointer arithmetic in loops, pointer increment, and passing pointers to functions, including examples for multi-dimensional and dynamic arrays.

Mastering these techniques is essential for advanced C programming, enabling you to handle dynamic memory, multi-dimensional structures, and complex algorithms effectively.

References & Additional Resources

A curated collection of textbooks, tutorials, and documentation for learning pointers and array manipulation in C.

  1. Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988 – The foundational text covering arrays, pointers, functions, and core C programming concepts.
  2. GeeksforGeeks: Pointer to an Array | Array Pointer – Explains how to use pointers to access and manipulate array elements efficiently.
  3. Tutorialspoint: C Pointers – Beginner-friendly guide to understanding pointers, their declaration, and usage in C.
  4. Cprogramming.com: Arrays and Pointers – Practical examples demonstrating how arrays and pointers interact in C.
  5. cplusplus.com: Pointer Arithmetic – Reference for pointer arithmetic and memory addressing in C programs.
Scroll to Top