0
0
CHow-ToBeginner · 3 min read

How to Pass Array to Function in C: Syntax and Examples

In C, you pass an array to a function by specifying the array name without brackets as a parameter, like void func(int arr[]) or void func(int *arr). Inside the function, the array is accessed via a pointer to its first element.
📐

Syntax

To pass an array to a function in C, you declare the function parameter as either an array or a pointer. Both ways let the function access the array elements.

  • void func(int arr[]): Declares arr as an array parameter.
  • void func(int *arr): Declares arr as a pointer to an integer.
  • Note: The array size is optional in the parameter.
c
void func(int arr[], int size) {
    // function body
}

// or equivalently

void func(int *arr, int size) {
    // function body
}
💻

Example

This example shows how to pass an integer array to a function and print its elements.

c
#include <stdio.h>

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

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int length = sizeof(numbers) / sizeof(numbers[0]);
    printArray(numbers, length);
    return 0;
}
Output
10 20 30 40 50
⚠️

Common Pitfalls

Common mistakes when passing arrays to functions include:

  • Forgetting to pass the array size, which is needed to avoid reading beyond the array.
  • Using sizeof inside the function to get array length, which does not work because the array decays to a pointer.
  • Modifying the array inside the function without realizing it affects the original array.
c
/* Wrong: Trying to get size inside function */
void printArrayWrong(int arr[]) {
    int size = sizeof(arr) / sizeof(arr[0]); // This gives wrong size
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

/* Right: Pass size as parameter */
void printArrayRight(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
📊

Quick Reference

Remember these tips when passing arrays to functions in C:

  • Pass the array name without brackets.
  • Always pass the array size separately.
  • Inside the function, the array parameter is treated as a pointer.
  • Modifications inside the function affect the original array.

Key Takeaways

Pass arrays to functions by using the array name without brackets as a parameter.
Always pass the array size separately to avoid out-of-bounds errors.
Inside the function, the array parameter acts as a pointer to the first element.
Modifying the array inside the function changes the original array.
Do not use sizeof inside the function to get array length; it returns pointer size.