How arrays are passed to functions in C/C++

In this tutorial, we will be discussing how arrays are passed to functions in C. Understanding this concept is crucial for proper array handling in C programming.

In C, arrays are never passed by value to functions. Instead, when you pass an array to a function, what actually gets passed is a pointer to the first element of the array. This is called "array decay" − the array name decays into a pointer.

Syntax

// Method 1: Array notation
void function_name(data_type array_name[]);

// Method 2: Pointer notation  
void function_name(data_type *array_name);

// Method 3: With size specification (ignored by compiler)
void function_name(data_type array_name[SIZE]);

Example: Demonstrating Array Decay

This example shows how sizeof() behaves differently when used on arrays in different scopes −

#include <stdio.h>

/* Function receives array as pointer */
void fun(int arr[]) {
    unsigned int n = sizeof(arr)/sizeof(arr[0]);
    printf("Array size inside fun() is %d\n", n);
    printf("sizeof(arr) inside fun() = %lu bytes\n", sizeof(arr));
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
    unsigned int n = sizeof(arr)/sizeof(arr[0]);
    printf("Array size inside main() is %d\n", n);
    printf("sizeof(arr) inside main() = %lu bytes\n", sizeof(arr));
    fun(arr);
    return 0;
}
Array size inside main() is 8
sizeof(arr) inside main() = 32 bytes
Array size inside fun() is 2
sizeof(arr) inside fun() = 8 bytes

Example: Proper Way to Pass Array Size

Since the function receives only a pointer, you must pass the array size separately −

#include <stdio.h>

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

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr)/sizeof(arr[0]);
    
    printf("Original array size: %d\n", size);
    printArray(arr, size);
    return 0;
}
Original array size: 5
Array elements: 10 20 30 40 50 

Key Points

  • Arrays are passed as pointers to the first element, not as complete arrays.
  • The sizeof() operator returns pointer size (8 bytes on 64-bit systems) inside functions.
  • Always pass array size as a separate parameter to functions.
  • Array modifications inside functions affect the original array (pass by reference behavior).

Conclusion

Arrays in C are passed to functions as pointers to their first element. This requires passing the array size separately and understanding that sizeof() won't work as expected inside functions. This mechanism allows efficient memory usage but requires careful handling of array bounds.

Updated on: 2026-03-15T12:44:50+05:30

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements