Course Content
Detailed Content of Programming in C
0/1
Introduction
0/1
Structure of C program
0/1
Answers of ‘C’ Pointers Programs
0/1
About Lesson

In C, arrays and pointers are closely related. An array name can be treated as a pointer to the first element of the array.

Definition:

An array pointer in C is a pointer that points to the first element of an array. Since array names decay into pointers to their first elements, you can use pointers to access elements of an array.

Syntax:

return_type (*pointer_name)(parameter_types);

Here, data_type is the type of the elements in the array, and pointer_name is the name of the pointer.

Example:

#include <stdio.h>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int *ptr; // Declare an integer pointer

    ptr = numbers; // Point the pointer to the first element of the array

    // Access elements of the array using the pointer
    printf(“Elements of the array: “);
    for (int i = 0; i < 5; i++) {
        printf(“%d “, *(ptr + i)); // Using pointer arithmetic to access elements
    }

    return 0;
}

Explanation:

  • int numbers[] = {1, 2, 3, 4, 5};: Declare and initialize an integer array.
  • int *ptr;: Declare an integer pointer.
  • ptr = numbers;: Point the pointer ptr to the first element of the array.
  • *(ptr + i): Use pointer arithmetic to access elements of the array.

Output:

Elements of the array: 1 2 3 4 5

In this program, the pointer ptr is used to access elements of the numbers array. The *(ptr + i) expression is equivalent to numbers[i]. Pointer arithmetic is used to iterate through the array elements.