c
  1. c-program-to-access-array-elements-using-pointer

Program to Access Array Elements Using Pointer - (C Programs)

In C programming, pointers are used to store and manipulate memory addresses. This allows for a wide range of operations, including accessing array elements using pointers. In this tutorial, we'll see an example of how to access array elements using pointers in C programming.

Syntax

The syntax for accessing array elements using pointers in C is as follows:

data_type *pointer_name;
pointer_name = &array_name[index];

Here, data_type specifies the data type of the array elements, pointer_name specifies the name of the pointer variable, &array_name[index] specifies the address of the element in the array that we want to access.

Example

Consider the following example, where we have an array of integers and we use pointers to access its elements:

#include <stdio.h>

void main() {
   int arr[5] = {10, 20, 30, 40, 50};
   int *ptr;

   /* Assigns the address of the first element of array to the pointer */
   ptr = arr;

   for(int i = 0; i < 5; i++) {
       printf("Value of arr[%d] = %d\n", i, *ptr);
       /* Moves the pointer to the next element of the array */
       ptr++;
   }
}

Output:

Value of arr[0] = 10
Value of arr[1] = 20
Value of arr[2] = 30
Value of arr[3] = 40
Value of arr[4] = 50

Explanation

In this program, we declare an integer array arr with 5 elements and initialize it with some values. We also declare a pointer variable ptr of type integer.

To access each element of the array using pointers, we assign the address of the first element of the array to the pointer using ptr = arr;.

We then use a loop to access each element one by one using the dereference operator (*) on the pointer variable *ptr and move the pointer to the next element of the array ptr++.

Use

The ability to use pointers to access array elements in C programming is a powerful feature with many use cases, such as:

  • Modifying array elements using pointers
  • Passing arrays to functions using pointers
  • Implementing data structures such as linked lists and trees

Summary

In this tutorial, we saw an example of how to access array elements using pointers in C programming. We covered the syntax, example, explanation, use, and advantages of using pointers to access array elements. By using pointers, we can perform many powerful memory operations and implement complex data structures in C programming.

Published on: