C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Pass array to function using pointers

C Program: Pass array to function using pointers

C

#include <stdio.h>

 

// Function declaration

void displayArray(int *arr, int size);

 

int main() {

    int arr[5];

    int i;

 

    // Input array elements

    printf("Enter 5 integers:\n");

    for (i = 0; i < 5; i++) {

        scanf("%d", &arr[i]);

    }

 

    // Pass array to function

    displayArray(arr, 5);

 

    return 0;

}

 

// Function definition

void displayArray(int *arr, int size) {

    int i;

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

    for (i = 0; i < size; i++) {

        printf("%d ", *(arr + i));  // Accessing array using pointer arithmetic

    }

    printf("\n");

}

Output

 
OUTPUT 1 :
Enter 5 integers:
10 20 30 40 50

Array elements are:
10 20 30 40 50

Explanation

  • In C, arrays are passed to functions as pointers — meaning only the address of the first element is passed.
  • Inside the function, arr behaves like a pointer to the first element of the array.
  • We use pointer arithmetic (*(arr + i)) to access elements.