Skip to main content

Accessing array elements using pointer

Short answer

Pointers hold addresses, enabling call by reference, dynamic memory, and efficient array handling. To access array elements, set a pointer to the array name (address of first element); then *(p+i) gives a[i], and pointer arithmetic like p++ traverses the array.

Explain how pointers can be used in C. How can you access array elements using pointer.

Use of pointers in C

A pointer is a variable holding the address of another variable. It is used for call by reference, dynamic memory allocation (malloc), efficient array and string handling, and building data structures such as linked lists and trees.

Accessing array elements with a pointer

The array name is the address of its first element, so a pointer can be set to it: int *p = a;. Then:

  • *p is a[0], *(p + 1) is a[1], and in general *(p + i) is a[i].
  • The pointer can be moved with p++ to visit the next element.
#include <stdio.h>

int main(void)
{
    int a[5] = {5, 10, 15, 20, 25}, *p = a, sum = 0;

    for (int i = 0; i < 5; i++)
        printf("a[%d] = %d\n", i, *(p + i));    /* value using pointer */

    for (p = a; p < a + 5; p++)                 /* moving the pointer */
        sum += *p;
    printf("Sum = %d\n", sum);
    return 0;
}

Output:

a[0] = 5
a[1] = 10
a[2] = 15
a[3] = 20
a[4] = 25
Sum = 75

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 9 questions →