Metadata

  • 📅 Date :: 09-06-2025
  • 🏷️ Tags :: cpp

Notes

Detailed Notes on Passing Arrays to Functions in C++

Passing arrays to functions is a common task in C++, and understanding how it works is essential to efficiently handling arrays. In this tutorial, we will break down how arrays are passed to functions and how to calculate the size of an array when it is passed. We will also cover how to work with arrays inside functions and some of the issues that may arise when dealing with array sizes.

1. Passing Arrays to Functions

When passing an array to a function in C++, you do not need to include the square brackets ([]). Instead, you just pass the array name, which is treated as a pointer to the first element of the array. This is known as “array decay.” It means the array is passed as a pointer to its first element, not as the entire array.

Example: Passing an Array to a Function

Let’s assume we have an array of double values representing prices:

double prices[] = {49.99, 15.05, 75.00, 9.99};  // Example prices
 

We need to create a function to calculate the total price of all the elements in the prices array.

Function Definition:

To pass the prices array to a function, we can define the function to accept a pointer (array) and its size.

double get_total(double prices[], int size) {
    double total = 0.0;
 
    // Loop through the array to calculate the total
    for (int i = 0; i < size; i++) {
        total += prices[i];  // Add the price at index i to total
    }
 
    return total;  // Return the total price
}
 
  • Function Parameters: double prices[] and int size.
    • prices[]: The array of doubles (prices).
    • size: The number of elements in the array.
  • Explanation:
    • Inside the get_total function, we iterate over the array using a for loop and sum up all the elements in the array.
    • The size of the array is provided explicitly as a parameter (size) since C++ does not keep track of the array’s size when it is passed as a pointer.

2. The Issue with Array Size

When passing an array to a function, the array “decays” into a pointer, meaning that the function no longer knows the size of the array. This presents a problem if you need to know the array’s size inside the function, as the size is not passed automatically.

The Array Decay Problem

When you pass an array, you’re actually passing a pointer to the first element of the array. The function cannot determine how many elements are in the array from the pointer alone. This is why the size of the array needs to be passed separately.

For example:

double get_total(double prices[]) {
    // Attempting to calculate size within the function doesn't work
    int size = sizeof(prices) / sizeof(prices[0]);  // This won't work
}
 
  • The above calculation doesn’t work because sizeof(prices) will give the size of the pointer (not the array itself), and sizeof(prices[0]) is the size of one element in the array.
  • Thus, it’s impossible to calculate the size of the array within the function using sizeof.

3. Fixing the Issue: Passing Array Size

To correctly calculate the total of the array elements, you should pass the size of the array as a second argument. The size can be calculated in the main function where the array is defined.

Example: Correcting the Function Call

First, we calculate the size of the array using sizeof in the main function:

int size = sizeof(prices) / sizeof(prices[0]);  // Calculate size of the array
 

Then, pass both the array and its size to the function:

double total = get_total(prices, size);  // Pass both the array and its size
 

The updated function now works as expected:

double get_total(double prices[], int size) {
    double total = 0.0;
 
    for (int i = 0; i < size; i++) {
        total += prices[i];
    }
 
    return total;
}
 

This ensures that the function correctly knows how many elements to iterate over.

Complete Program Example:

#include <iostream>
 
double get_total(double prices[], int size) {
    double total = 0.0;
 
    for (int i = 0; i < size; i++) {
        total += prices[i];
    }
 
    return total;
}
 
int main() {
    double prices[] = {49.99, 15.05, 75.00, 9.99};
    int size = sizeof(prices) / sizeof(prices[0]);  // Calculate the number of elements
 
    double total = get_total(prices, size);  // Pass array and size to the function
 
    std::cout << "Total: $" << total << std::endl;
 
    return 0;
}
 

Output:

Total: $150.03

4. Key Points to Remember

  • When passing an array to a function in C++, the array decays into a pointer to its first element.
  • C++ does not automatically pass the size of the array, so you must manually pass the size of the array as a separate argument to the function.
  • You can calculate the size of an array in the caller function (e.g., sizeof(prices) / sizeof(prices[0])).
  • Inside the function, you can then use the size argument to iterate over the array elements.

5. Conclusion

To summarize:

  • Passing an array: When an array is passed to a function, you only need to pass the array name (it becomes a pointer).
  • Size of the array: You must manually pass the size of the array as an argument, as the function does not automatically know its size.
  • Using the array: Inside the function, you can access and manipulate the array elements using the pointer and the size.

By passing both the array and its size to the function, you can safely iterate over the array and perform operations like summing its elements.


References