In C++, an array represents a grouping of elements that are held in a continuous memory block and share a common data type. In C++, an array can be transferred to functions using either a pointer or a reference. The primary purpose of passing arrays to functions is to execute various tasks on array elements effectively, enhancing the organization of the codebase.
In C++, when we aim to recycle array logic, we can establish a function. Only the array name is required to be supplied for passing an array to a function in C++.
Syntax
It has the following syntax:
Return_type function_name(data_ype array_name); //passing array to function
C++ Passing Array to Function Example: print array elements
Here is an example of a C++ function that displays the elements of an array.
Example
#include <iostream>
using namespace std; //using standard namespace
void printArray(int arr[5]);
int main() //main function
{
int arr1[5] = { 10, 20, 30, 40, 50 };
int arr2[5] = { 5, 15, 25, 35, 45 };
printArray(arr1); //passing array to function
printArray(arr2);
}
void printArray(int arr[5])
{
cout << "Printing array elements:"<< endl;
for (int i = 0; i < 5; i++)
{
cout<<arr[i]<<"\n";
}
}
Output:
Printing array elements:
10
20
30
40
50
Printing array elements:
5
15
25
35
45
Methods to Passing an Array to Function in C++
There are several methods that we can use to pass an array to function in C++. Some main methods are as follows:
- Passing Array as a Pointer
- Passing array as a Reference
- Passing as a Sized Array
- Passing as an Unsized Array
Passing Array as a Pointer
In C++, the most prevalent and effective approach for passing an array to a function is by passing it as a pointer. This technique involves sending the memory address of the first element of the array, enabling the function to work with arrays of varying sizes dynamically.
Syntax
It has the following syntax:
returntype functionname (datatype *array_name)
In this syntax,
- functionname: It represents the name of the function.
- datatype: It represents the type of data.
- *array_name: It represents the pointer array.
C++ Passing Array as a Pointer Example
Let's consider an example to illustrate how we can send an array as a pointer in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
void show(int *arr, int size) { // Function to print elements of the array
cout << "Array elements are: ";
for (int i = 0; i < size; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main() { //main function
int num[] = {5, 10, 15, 20, 25, 30};
int size = sizeof(num) / sizeof(num[0]);
// Passing array as a pointer
show(num, size);
return 0;
}
Output:
Array elements are: 5 10 15 20 25 30
Explanation:
In this instance, we are passing the int *arr parameter in the display function, which accepts the starting address of the array of integers. Subsequently, the array transforms into a pointer, allowing the arr[i] operation to interact with elements using pointer calculations. Additionally, we provide the size parameter to specify the quantity of elements in the array.
Passing Array as a Reference
In C++, one commonly utilized technique is passing an array by reference to a function. This approach is crucial for preserving the array's size and preventing pointer decay. By doing so, the function receives a direct link to the original array, granting it the ability to both retrieve and alter the array's elements while retaining information about its size during compilation.
Syntax
It has the following syntax:
returntype functionname(datatype (&arr_name)[size])
Passing an array as a reference to a function in C++ allows the function to directly access and modify the original array. This can be done by specifying the array parameter with square brackets indicating the array size or with a pointer parameter. Here is an example illustrating how to pass an array as a reference to a function in C++:
#include <iostream>
using namespace std;
// Function to modify the array elements
void modifyArray(int (&arr)[5]) {
for(int i = 0; i < 5; i++) {
arr[i] *= 2; // Doubling each element
}
}
int main() {
int myArray[5] = {1, 2, 3, 4, 5};
cout << "Original Array: ";
for(int i = 0; i < 5; i++) {
cout << myArray[i] << " ";
}
modifyArray(myArray); // Passing array as a reference
cout << "\nModified Array: ";
for(int i = 0; i < 5; i++) {
cout << myArray[i] << " ";
}
return 0;
}
In this example, the modifyArray function takes an array arr as a reference, allowing it to directly modify the elements of the original array passed from the main function.
Let us take an example to illustrate we can pass an array as a reference to a function in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
// Function taking array as reference
void print_array(int (&arr)[5]) {
cout << "Array elements are: ";
for (int i = 0; i < 5; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main() { //main function
int number[5] = {12, 25, 16, 30, 34};
// Pass array by reference
print_array(number);
return 0;
}
Output:
Array elements are: 12 25 16 30 34
Explanation:
In this instance, we are examining the print_array function, which accepts an array containing 5 integers by reference to maintain the array's size. Subsequently, it displays each element of the array using a for loop. This approach effectively avoids pointer decay and allows direct access to the original array.
Passing as a Sized Array to Function
In C++, it is a prevalent practice to pass a sized array to a function when needing to transfer an array for processing. By indicating the array's size in the function's parameter list, we refer to this technique as passing a sized array. Nonetheless, during the passage, the array transforms into a pointer, a behavior that retains the size information necessary for accessing the precise quantity of elements.
Syntax
It has the following syntax:
returntype FunctionName (datatype arrName [size], int size)
C++ Passing as a Sized Array to Function Example
Let's consider an example to illustrate how we can pass an array of a specific size to a function in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
// Function taking array as a sized array
void show(int arr[5]) {
cout << "Elements in the array: ";
for (int i = 0; i < 5; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main() { //main function
int nums[5] = {4, 8, 12, 20, 25};
show(nums); // Passing array
return 0;
}
Output:
Elements in the array: 4 8 12 20 25
Explanation
In this instance, we are examining the show method which is designed to operate on a static array containing 5 integers. However, within the main function, an array named nums is declared with 6 elements. Within the show function, the loop attempts to reach 6 elements, resulting in unpredictable behavior as accessing arr[5] extends beyond the defined size of the array parameter.
Passing as an Unsized Array
In C++, passing as an unsized array to a function is similar to passing as a sized array. We can pass an unsized array to a function by avoiding the size in the parameter declaration.
Syntax
It has the following syntax:
return_type function_name (data_type array_name[])
Passing an Unsized Array to a Function in C++ Example:
Return_type function_name(data_ype array_name); //passing array to function
#include <iostream>
// Function that takes an unsized array and its size as parameters
void processArray(int* arr, int size) {
for(int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
}
int main() {
int myArray[] = {1, 2, 3, 4, 5};
// Calculating the size of the array
int size = sizeof(myArray) / sizeof(myArray[0]);
// Passing the unsized array to the function
processArray(myArray, size);
return 0;
}
In this example, the processArray function takes an unsized array arr and its size size as parameters. Inside the function, a loop iterates through the elements of the array and prints them. The main function creates an array myArray, calculates its size, and then passes the unsized array along with its size to the processArray function for processing.
Let's consider an example to illustrate how we can pass an array without a specified size to a function in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
// Function taking unsized array
void show(int arr[], int size) {
cout << "Unsized Array elements are: ";
for (int i = 0; i < size; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main() { //main function
int nums[] = {7, 14, 21, 28, 35};
int len = sizeof(nums) / sizeof(nums[0]);
show(nums, len); // Pass array and its size
return 0;
}
Output:
Unsized Array elements are: 7 14 21 28 35
Explanation:
In this instance, we are demonstrating the show method that receives an unbounded array (int arr) and its dimension as arguments. Subsequently, the nums array is supplied along with its size, enabling the method to iterate over each item and present them.
C++ Example to Pass Multidimensional Array to a Function
Let's consider an example to illustrate how we can send a multi-dimensional array as an argument to a function in C++.
Example
#include <iostream>
using namespace std; // using standard namespace
void printMatrix(int arr[3][2]) //function using 2D array with 3 row and 2 columns
{
cout << "Elements of Matrix are:" << endl;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 2; ++j) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main() { // main function
int matrix[3][2] = {
{9, 8},
{7, 6},
{5, 4}
};
// Passing 2D array to function
printMatrix(matrix);
return 0;
}
Output:
Elements of Matrix are:
9 8
7 6
5 4
Explanation:
In this instance, a 3×2 two-dimensional array is provided as input to the printMatrix function. Subsequently, the function iterates through a predetermined 2D array using nested loops to display each element.
C++ Passing an Array to Function FAQs
1) Can we pass an array to a function in C++?
Yes, arrays can be passed to functions using pointers or references in the C++ programming language.
2) Can we change array elements within a function in C++?
Yes, it is possible to modify the elements of an array within a function; however, such changes may impact the original array.
3) Can we use the sizeof function inside a function to find the size of the array in C++?
No, the sizeof function solely operates within the invoking function.
4) How can we pass an array using the reference in C++?
In C++, we have the ability to transmit an array by reference using the subsequent syntax:
void func(int (&arr)[5])
5) What are the several methods to pass an array to a function in C++?
There exist various techniques for transmitting an array to a function in C++, including sending a pointer, transmitting as a reference, conveying as a sized array, and passing as an unsized array.