#include <iostream>
using namespace std;
void display(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
display(numbers, 5);
return 0;
}Passing C++ Arrays to Functions: Parameter Techniques and Examples
Direct Answer & Core Concept
Arrays are used in C++ to store multiple values of the same data type in a single variable. When working with large programs, you may need to process an array in different parts of your application.
Instead of writing the same array-processing code repeatedly, you can pass an array to a function.
For example, you can create separate functions to:
Display array elements.
Calculate the sum and average.
Find the largest or smallest element.
Search for a particular value.
Update array elements.
Sort an array.
Detailed Explanation & Mechanics
1. What Does Passing an Array to a Function Mean?
Passing an array to a function means providing the function with access to the array elements so it can perform a particular operation.
Consider this example:
Output:
10 20 30 40 50Explanation:
The
numbersarray is declared insidemain().The
display()function receives the array through its parameterint arr[].The
sizeparameter tells the function how many elements to process.The loop accesses each element and displays it.
Important: When a built-in array is passed to a function using an ordinary array parameter, the parameter is adjusted to a pointer type. The function does not receive a separate copy of the entire array.
2. Syntax for Passing an Array to a Function
The general syntax is:
return_type function_name(data_type array_name[], int size) {
// Function body
}Example:
void display(int arr[], int size) {
// Process array elements
}Here:
voidmeans the function does not return a value.displayis the function name.int arr[]represents an integer array parameter.sizerepresents the number of elements.
You can also write the parameter using pointer notation:
void display(int* arr, int size);For an ordinary function parameter, these declarations are equivalent:
void display(int arr[], int size);
void display(int* arr, int size);Both allow the function to access the elements through the pointer.
3. Passing a One-Dimensional Array to a Function
A one-dimensional array is the simplest type of array to pass to a function.
Example 1: Display Array Elements
#include <iostream>
using namespace std;
void displayArray(int arr[], int size) {
cout << "Array elements: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
displayArray(numbers, 5);
return 0;
}Output:
Array elements: 10 20 30 40 50The function receives access to the original array elements. It can read or modify them.
Example 2: Calculate the Sum of Array Elements
#include <iostream>
using namespace std;
int calculateSum(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
int result = calculateSum(numbers, 5);
cout << "Sum: " << result;
return 0;
}Output:
Sum: 150Explanation:
The
calculateSum()function receives the array and its size.The loop adds every element to
sum.The function returns the calculated total.
The result is displayed in
main().
Example 3: Find the Largest Element
#include <iostream>
using namespace std;
int findLargest(int arr[], int size) {
int largest = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
int main() {
int numbers[5] = {25, 10, 75, 40, 60};
cout << "Largest element: "
<< findLargest(numbers, 5);
return 0;
}Output:
Largest element: 75The function starts with the first element as the largest value and compares the remaining elements against it.
This example assumes the array contains at least one element.
4. Passing an Array Using Pointer Parameters
In C++, an array parameter is adjusted to a pointer parameter. You can explicitly use pointer notation when declaring the function.
Example: Access Array Elements Using Pointers
#include <iostream>
using namespace std;
void displayArray(int* ptr, int size) {
for (int i = 0; i < size; i++) {
cout << *(ptr + i) << " ";
}
}
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
displayArray(numbers, 5);
return 0;
}Output:
10 20 30 40 50Explanation:
int* ptrdeclares a pointer parameter.ptrpoints to the first element when the array is passed.*(ptr + i)accesses the element at positioni.*(ptr + i)is equivalent toptr[i].
Pointer notation is useful when learning how arrays and memory addresses work in C++.
5. Modifying an Array Inside a Function
When a function receives a built-in array through an ordinary array parameter, it can modify the original elements.
Example: Update Array Elements
#include <iostream>
using namespace std;
void updateArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] = arr[i] * 2;
}
}
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
updateArray(numbers, 5);
cout << "Updated array: ";
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
return 0;
}Output:
Updated array: 2 4 6 8 10The function changes the original array elements because the parameter provides access to the same underlying elements.
Important: Passing an Array Does Not Copy Its Elements
Compare these two situations:
void update(int arr[], int size) {
arr[0] = 100;
}The function changes the original array's first element.
However, a normal pointer parameter is still passed by value. If you assign a different address to the local pointer parameter, the caller's pointer or array is not changed.
For example:
void changePointer(int* ptr) {
int temporary = 500;
ptr = &temporary;
}This only changes the local pointer variable. It does not change the caller's array.
6. Passing an Array as a Constant Parameter
Sometimes you want a function to read array elements without modifying them.
You can use the const keyword.
Syntax
void display(const int arr[], int size);Example: Read-Only Array Function
#include <iostream>
using namespace std;
void displayArray(const int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
int main() {
int numbers[4] = {10, 20, 30, 40};
displayArray(numbers, 4);
return 0;
}Output:
10 20 30 40The const keyword prevents the function from modifying the elements through this parameter.
For example, the following assignment would cause a compilation error:
void display(const int arr[], int size) {
arr[0] = 100; // Compilation error
}Best practice: Use const for functions that only need to read an array. This makes the function's intention clear and prevents accidental modification.
7. Passing an Array by Reference
C++ also allows you to pass an entire built-in array by reference.
Unlike an ordinary array parameter, a reference-to-array parameter retains the array's size as part of its type.
Syntax
void display(int (&arr)[5]);This parameter accepts an array containing exactly five integers.
Example: Pass an Array by Reference
#include <iostream>
using namespace std;
void display(int (&arr)[5]) {
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
}
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
display(numbers);
return 0;
}Output:
10 20 30 40 50Explanation:
int (&arr)[5]declares a reference to an array of five integers.The function receives the actual array without array-to-pointer adjustment.
The size is known from the parameter type.
The function can modify the original elements unless the reference is declared
const.
A read-only version is:
void display(const int (&arr)[5]);This approach is useful when the array size is fixed and you want the compiler to enforce that size.
8. Passing an Array to a Function Using a Template
Templates allow you to write functions that can work with arrays of different sizes without manually specifying the size in each function call.
Example: Array Size Template
#include <iostream>
using namespace std;
template <size_t N>
void displayArray(const int (&arr)[N]) {
for (size_t i = 0; i < N; i++) {
cout << arr[i] << " ";
}
}
int main() {
int first[3] = {10, 20, 30};
int second[5] = {1, 2, 3, 4, 5};
displayArray(first);
cout << endl;
displayArray(second);
return 0;
}Output:
10 20 30
1 2 3 4 5Explanation:
Nrepresents the array size.The compiler determines
Nfrom the array passed to the function.The array is passed by reference, so its size is preserved.
The same function works with both arrays.
This technique is useful when working with fixed-size built-in arrays of different lengths.
9. Passing a Two-Dimensional Array to a Function
A two-dimensional array contains rows and columns. When passing a built-in 2D array to a function using an ordinary array parameter, the compiler must know the number of columns.
Syntax
void display(int arr[][3], int rows);Here:
arr[][3]represents a 2D integer array with three columns.rowsrepresents the number of rows.
Example: Display a 2D Array
#include <iostream>
using namespace std;
void displayMatrix(int arr[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main() {
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
displayMatrix(matrix, 2);
return 0;
}Output:
10 20 30
40 50 60The function receives the array and its row count. The column count is specified in the parameter type.
Example: Calculate the Sum of a 2D Array
#include <iostream>
using namespace std;
int calculateSum(int arr[][3], int rows) {
int sum = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
sum += arr[i][j];
}
}
return sum;
}
int main() {
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
cout << "Total sum: "
<< calculateSum(matrix, 2);
return 0;
}Output:
Total sum: 21010. Passing a Three-Dimensional Array to a Function
A three-dimensional built-in array uses three indexes. As with a 2D array, the dimensions after the first must be specified in an ordinary function parameter.
Syntax
void display(int arr[][2][3], int layers);Here, the array contains two rows and three columns per layer. The number of layers is supplied separately.
Example: Display a 3D Array
#include <iostream>
using namespace std;
void display3D(int arr[][2][2], int layers) {
for (int i = 0; i < layers; i++) {
cout << "Layer " << i + 1 << ":" << endl;
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
cout << arr[i][j][k] << " ";
}
cout << endl;
}
}
}
int main() {
int data[2][2][2] = {
{
{10, 20},
{30, 40}
},
{
{50, 60},
{70, 80}
}
};
display3D(data, 2);
return 0;
}Output:
Layer 1:
10 20
30 40
Layer 2:
50 60
70 80The function processes each layer, row, and column using three nested loops.
11. Passing Array Size to a Function
One important detail in C++ is that an ordinary built-in array parameter does not automatically retain the original array length.
Consider:
void display(int arr[]) {
// The original array size is not available here.
}Inside this function, arr is a pointer parameter. You cannot use sizeof(arr) to determine the size of the original array.
Recommended Approach: Pass the Size Separately
#include <iostream>
using namespace std;
void display(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
int main() {
int numbers[] = {10, 20, 30, 40};
int size = sizeof(numbers) / sizeof(numbers[0]);
display(numbers, size);
return 0;
}Output:
10 20 30 40The sizeof calculation works in main() because numbers is still an array there. The function receives the calculated size separately.
For fixed-size built-in arrays in C++17 and later, std::size(numbers) from the <iterator> header is another option.
12. Passing Arrays Using std::array and std::vector
Modern C++ provides standard containers that make array handling easier and safer.
12.1 Passing std::array to a Function
std::array is a fixed-size container that retains its size and provides useful member functions.
#include <iostream>
#include <array>
using namespace std;
void display(const array<int, 5>& numbers) {
for (int value : numbers) {
cout << value << " ";
}
}
int main() {
array<int, 5> numbers = {10, 20, 30, 40, 50};
display(numbers);
return 0;
}Output:
10 20 30 40 50The const reference avoids copying the container and prevents the function from modifying its elements.
12.2 Passing std::vector to a Function
std::vector is a dynamic container that can grow or shrink during program execution.
#include <iostream>
#include <vector>
using namespace std;
void display(const vector<int>& numbers) {
for (int value : numbers) {
cout << value << " ";
}
}
int main() {
vector<int> numbers = {10, 20, 30, 40, 50};
display(numbers);
return 0;
}Output:
10 20 30 40 50The function receives the vector by constant reference, avoiding a full copy.
When should you use each approach?
Use built-in arrays when working with fixed-size low-level data.
Use
std::arraywhen the size is fixed and you want a standard container.Use
std::vectorwhen the size may change at runtime.
13. Different Techniques for Passing Arrays to Functions
The following table summarizes the most common techniques.
| Technique | Example parameter | Main characteristic |
|---|---|---|
| Array parameter | int arr[] | Adjusted to a pointer |
| Pointer parameter | int* arr | Provides access through a pointer |
| Constant array parameter | const int arr[] | Read-only access to elements |
| Array reference | int (&arr)[5] | Preserves the array type and size |
| Template array reference | const int (&arr)[N] | Preserves size for different arrays |
std::array reference | const array<int, 5>& | Fixed-size standard container |
std::vector reference | const vector<int>& | Dynamic-size standard container |
14. Common Mistakes When Passing Arrays to Functions
Mistake 1: Forgetting to Pass the Array Size
void display(int arr[], int size);
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
display(numbers); // Incorrect: missing size argument
}The function expects two arguments. Pass both the array and its size.
Mistake 2: Using sizeof() Inside the Function to Find Array Length
void display(int arr[]) {
int size = sizeof(arr) / sizeof(arr[0]);
}This does not calculate the original array length because arr is a pointer parameter.
Pass the size separately or use an array-reference template.
Mistake 3: Accessing Elements Outside the Array
void display(int arr[], int size) {
for (int i = 0; i <= size; i++) {
cout << arr[i];
}
}The loop condition should be i < size, not i <= size.
Accessing an element outside the valid range causes undefined behavior.
Mistake 4: Trying to Modify a const Array
void update(const int arr[], int size) {
arr[0] = 100; // Compilation error
}A const array parameter allows reading but not modifying elements through that parameter.
Mistake 5: Passing a 2D Array With the Wrong Column Size
void display(int arr[][3], int rows);This parameter expects three columns. A 2D array with a different column count cannot be passed as though it had three columns.
Make sure the parameter dimensions match the array type.
Mistake 6: Passing an Empty Array to a Function That Reads Its First Element
A function such as findLargest() that starts with arr[0] requires at least one element.
Check that the size is greater than zero before accessing the first element.
15. Best Practices for Passing Arrays to Functions
Follow these practices when designing array-processing functions:
Pass the array size whenever using an ordinary built-in array parameter.
Use
constwhen a function only needs to read elements.Use a reference-to-array template when you need the built-in array size at compile time.
Use
std::arrayfor fixed-size collections.Use
std::vectorfor dynamically sized collections.Avoid accessing elements outside the valid array range.
Keep array-processing functions focused on one task.
Validate sizes before accessing elements.
Use meaningful function and parameter names.
Prefer standard containers for general-purpose application development.
16. Frequently Asked Questions (FAQs)
1. Can we pass an array to a function in C++?
Yes. You can pass a built-in array to a function using an array parameter, pointer parameter, or reference-to-array parameter.
2. Does C++ pass an array by value or reference?
An ordinary built-in array parameter is adjusted to a pointer parameter. The pointer is passed by value, but it provides access to the original array elements.
3. How do you pass an array to a function using pointers?
Declare the function parameter using pointer notation:
void display(int* arr, int size);Pass the array name and its size when calling the function.
4. Can a function modify an array passed to it?
Yes. An ordinary array parameter provides access to the original elements, so changes made through that parameter affect the original array.
5. How do you pass an array without allowing modification?
Use a constant array parameter:
void display(const int arr[], int size);6. Why should we pass the array size separately?
An ordinary built-in array parameter is adjusted to a pointer. The function does not automatically know the original array length.
7. Can we pass a 2D array to a function?
Yes. For an ordinary built-in 2D array parameter, specify the column dimension:
void display(int arr[][3], int rows);8. Can we pass a 3D array to a function?
Yes. Specify the second and third dimensions in the parameter type:
void display(int arr[][2][3], int layers);9. What is the difference between int arr[] and int* arr in a function parameter?
For an ordinary function parameter, both declarations are adjusted to the same pointer type.
10. Is std::vector better than a built-in array?
It depends on the requirement. std::vector is useful for dynamically sized data, while built-in arrays and std::array are useful for fixed-size data.
11. Can we return an array directly from a C++ function?
A built-in array cannot be returned directly by value as a function return type. You can return a suitable container such as std::array or std::vector, or use other designs involving references or pointers with careful lifetime management.
12. What is the safest way to pass an array to a function in modern C++?
For fixed-size data, consider passing std::array by constant reference. For dynamically sized data, consider passing std::vector by constant reference when the function only needs to read it.
Runnable Code Example: Passing C++ Arrays to Functions
C++20 / C++23#include <iostream>
#include <span>
#include <vector>
// Modern C++20 std::span accepts raw arrays, std::array, or std::vector
void printElements(std::span<const int> buffer) {
std::cout << "Buffer (size: " << buffer.size() << "): ";
for (int val : buffer) {
std::cout << val << " ";
}
std::cout << "
";
}
int main() {
int rawArray[] = {1, 2, 3, 4};
std::vector<int> dynamicVec = {10, 20, 30, 40, 50};
printElements(rawArray); // Automatically creates span from raw array
printElements(dynamicVec); // Automatically creates span from vector
return 0;
}