How to use pointer variables to point to array elements in the C language?

In the C programming language, we can use pointer variables to point to array elements. This can be achieved by following these steps:

  1. Declare a pointer variable. For example, int *ptr; declares a pointer variable that points to data of integer type.
  2. Point the pointer variable to the first element of the array. For example, ptr = &array[0]; Point the pointer variable ptr to the first element of the array.
  3. Accessing array elements using pointer variables can be done by using the * operator to access the value pointed to by the pointer variable. For instance, *ptr will access the array element pointed to by the pointer variable ptr.

Here is a complete example:

#include <stdio.h>

int main() {
    int array[5] = {1, 2, 3, 4, 5};
    int *ptr;

    ptr = &array[0];

    for (int i = 0; i < 5; i++) {
        printf("Element %d: %d\n", i, *ptr);
        ptr++;
    }

    return 0;
}

In the example mentioned above, a pointer variable *ptr pointing to an integer data type is first declared. It is then initialized to point to the first element of the array. Next, the array element pointed to by *ptr is accessed, and within a loop, the pointer variable ptr is incremented to access the next element in the array.

bannerAds