Skip to main content

Passing Arrays to Functions in C

In C, arrays can be passed to functions to perform operations like searching, sorting, and modifying elements. Unlike regular variables, arrays are passed by reference — the function receives the address of the first element, not a copy. This means any changes made inside the function will affect the original array.

Syntax

return_type function_name(data_type array_name[], int size);

Example: Display Array Elements

#include <stdio.h>

void displayArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    printf("Array elements: ");
    displayArray(numbers, 5);
    return 0;
}
// Output: Array elements: 10 20 30 40 50

Example: Modify Array Inside a Function

#include <stdio.h>

void doubleElements(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        arr[i] *= 2;   // modifies the original array
    }
}

int main() {
    int nums[4] = {1, 2, 3, 4};
    doubleElements(nums, 4);
    for (int i = 0; i < 4; i++) {
        printf("%d ", nums[i]);
    }
    return 0;
}
// Output: 2 4 6 8

Example: Find the Sum of an Array

#include <stdio.h>

int sumArray(int arr[], int size) {
    int total = 0;
    for (int i = 0; i < size; i++) {
        total += arr[i];
    }
    return total;
}

int main() {
    int marks[5] = {80, 90, 75, 85, 70};
    int total = sumArray(marks, 5);
    printf("Total marks = %d", total);
    return 0;
}
// Output: Total marks = 400

Important Points

  • Arrays are always passed to functions by reference (pointer to the first element)
  • The size must be passed as a separate argument — there is no built-in way to get the size inside the function
  • Changes made to the array inside the function do affect the original array
  • To prevent modification, use the const qualifier: void display(const int arr[], int size)