The Wayback Machine - https://web.archive.org/web/20240930225600/https://www.geeksforgeeks.org/pass-array-to-functions-in-cpp/
Open In App

Pass Array to Functions in C++

Last Updated : 03 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, a collection of elements stored in contiguous memory locations and having the same data type is called an array. Passing arrays to functions is done to perform various operations on array elements without messing up with the main code.

In C++, an array can be passed in a function using a pointer or reference. Understanding the different approaches to pass arrays is important for writing code according to the needs.

Methods to Pass Array to a Function in C++

In C++, we have the following ways to pass an array as a parameter to the function:

  1. As a sized array
  2. As an unsized array
  3. As a pointer (pass by pointer)
  4. As a reference (pass by reference)

1. Passing as a Sized Array

In this method, we pass the array in the same way we declare it with the array type, name, and size. As we can see, we still have to pass the size of the array as another parameter because at the end, the array will be treated as a pointer in the function.

Syntax

return_type function_name (datatype array_name [size], int size)

Example

The below example demonstrates the passing of array as sized array.

C++
// C++ program to demonstrate the passing of array as sized
// array.

#include <iostream>
using namespace std;

// function to update array elements
void printarray(int a[10])
{
    for (int i = 0; i < 5; i++)
        a[i] = a[i] + 5;
}

int main()
{
    // array declaration
    int a[5] = { 1, 2, 3, 4, 5 };
    printarray(a); // Passing array to function

    // printing array elements
    for (int i = 0; i < 5; i++)
        cout << a[i] << " ";
    return 0;
}

Output
6 7 8 9 10 

2. Passing as an Unsized Array

This method is similar to the previous method, but the difference is that we dont specify the size of the array.

Syntax

return_type function_name (data_type array_name[])

Example

The below example demonstrates the passing of array as unsized array.

C++
// C++ program to demonstrate the passing of array as
// unsized array.

#include <iostream>
using namespace std;

// function to update array elements
void printarray(int a[],int size)
{
    for (int i = 0; i < size; i++)
        a[i] = a[i] + 5;
}

int main()
{
    // array creation
    int a[5] = { 1, 2, 3, 4, 5 };
    int n=5;
    printarray(a,n); // Passing array to function

    // printing array elements
    for (int i = 0; i < n; i++)
        cout << a[i] << " ";
    return 0;
}

Output
6 7 8 9 10 

3. Passing Array as a Pointer

In this method, we pass the memory address of the first element of the array. This method also allows for dynamic array sizes.

Syntax

return_type function_name (datatype *array_name)

Example

The below example demonstrates how to pass array as a pointer to function.

C++
// C++ program to demonstratethe passing of array by
// pointer.

#include <iostream>
using namespace std;

// function to print array elements
void printarray(int* a)
{
    for (int i = 0; i < 5; i++)
        *(a + i) = *(a + i) + 5;
}

int main()
{
    // array creation
    int a[5] = { 1, 2, 3, 4, 5 };
    printarray(a); // Passing array to function
    for (int i = 0; i < 5; i++)
        cout << a[i] << " ";
    return 0;
}

Output
6 7 8 9 10 

4. Passing Array as a Reference

In this method, we pass an array to a function as a reference and also explicitly pass its size i.e. we are passing both the reference to the first element and the size of the array.

Syntax

return_type function_name(data_type (&arr)[size])

Example

C++
// C++ to demonstrate array passing by pass by reference
#include <iostream>
using namespace std;

void modifyArray(int (&arr)[5])
{
  // deducing size
  int size = sizeof(arr) / sizeof(int);
    for (int i = 0; i < size; ++i) {
        arr[i] *= 2;
    }
}

int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int n = 5;
    modifyArray(arr);
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output
2 4 6 8 10 

FAQs on Passing Array to Function in C++

Q1. What is the difference between pass by pointer and pass by reference for array?

Answer:

In pass by pointer, we pass the address of the first element. In pass by reference we need to pass both the reference to the first element and, if specified, the size of the array.

Also, in pass by pointer method, array decay occurs, but not in pass by reference method.

Q2. Can we modify the original array inside a function?

Answer:

Yes, if modifications are made to the array inside a function then it will affect the original array as the arrays can only be passed by pointer or reference.

Q3. Can passing of an array to a function be done using std::array(in C++17 or later)?

Answer:

Yes, using std::array you can pass array with size information as the std::array is a container instead of plain old datatype Arrays.



Similar Reads

C++ Functions - Pass By Reference
Several ways exist in which data (or variables) could be sent as an argument to a function. Two of the common ones are Passing by Value and Passing by Reference. Passing by reference allows a function to modify a variable without creating a copy. We have to declare reference variables. The memory location of the passed variable and parameter is the
5 min read
How to pass a 2D array as a parameter in C?
This post is an extension of How to dynamically allocate a 2D array in C? A one dimensional array can be easily passed as a pointer, but syntax for passing a 2D array to a function can be difficult to remember. One important thing for passing multidimensional arrays is, first array dimension does not have to be specified. The second (and any subseq
3 min read
Pass By Reference In C
Passing by reference is a technique for passing parameters to a function. It is also known as call by reference, call by pointers, and pass by pointers. In this article, we will discuss this technique and how to implement it in our C program. Pass By Reference in C In this method, the address of an argument is passed to the function instead of the
4 min read
When Do We Pass Arguments by Reference or Pointer in C++?
In C++, we can pass arguments to a function as a value, reference (or pointer). Each method has its unique benefits and uses. In this article, we will discuss the application or cases where we should pass the arguments by reference or a pointer. But first, let’s quickly revisit the definitions of pointers and references. Pointers in C++ Pointers ar
4 min read
Virtual Functions in Derived Classes in C++
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function. In C++, once a member function is declared as a virtua
2 min read
How to write C functions that modify head pointer of a Linked List?
Consider simple representation (without any dummy node) of Linked List. Functions that operate on such Linked lists can be divided into two categories: 1) Functions that do not modify the head pointer: Examples of such functions include, printing a linked list, updating data members of nodes like adding given a value to all nodes, or some other ope
4 min read
Virtual Functions and Runtime Polymorphism in C++
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overridden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique falls under Runtime Polymorphi
8 min read
abs(), labs(), llabs() functions in C/C++
abs(), labs(), llabs() functions are defined in cstdlib header file. These functions return the absolute value of integer that is input to them as their argument. abs() function: Input to this function is value of type int in C and value of type int, long int or long long int in C++. In C output is of int type and in C++ the output has same data ty
2 min read
Algorithm Library Functions in C++ STL
Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Find element in rangestd :: find_if_not : Find elemen
4 min read
asin() and atan() functions in C/C++ with Example
In C++, asin() and atan() is a predefined function used for mathematical calculations. math.h is the header file required for various mathematical functions. All the functions available in this library take double as an argument and return double as the result. asin() Method asin() function is used to find the arc sine of a number means give a sin
3 min read
Explicitly Defaulted and Deleted Functions in C++ 11
Defaulted Function What is a Defaulted Function? Explicitly defaulted function declaration is a new form of function declaration that is introduced into the C++11 standard which allows you to append the '=default;' specifier to the end of a function declaration to declare that function as an explicitly defaulted function. This makes the compiler ge
5 min read
beta(), betaf() and betal() functions in C++ STL
The beta(), betaf() and betal() are built-in functions in C++ STL that are used to compute the beta functionof two positive real values. The function takes two variables x and y as input and returns the beta function of x and y. Beta function (Also known as Euler integral of first kind) of x and y can be defined as: [Tex]$$B(x, y)=\int_0^1 t^{x-1}
3 min read
C String Functions
The C string functions are built-in functions that can be used for various operations and manipulations on strings. These string functions can be used to perform tasks such as string copy, concatenation, comparison, length, etc. The <string.h> header file contains these string functions. In this article, we will discuss some of the most commo
8 min read
__builtin_inf() functions of GCC compiler
These functions do not need to include any header file to use them. So it provides faster usage, as these are Built-in functions of GCC compiler which is most used compiler, even in competitive programming. Note: If the compiler shows warning of overflow, use casting before __builtin_inf() function as (data_type)__builtin_inf() 1. __builtin_inf(voi
4 min read
Methods vs. Functions in C++ with Examples
A method is a procedure or function in OOPs Concepts. Whereas, a function is a group of reusable code which can be used anywhere in the program. This helps the need for writing the same code again and again. It helps programmers in writing modular codes. Methods: A method also works the same as that of function. A method is defined inside a class.
3 min read
Top 10 Most Used Inbuilt C++ functions for Competitive Programming
In this article, we will discuss about the 10 most used inbuilt functions of C++ which will help you to save time and make code concise as well during competitive programming. List of top 10 inbuilt functions in C++ pow()sqrt()min()max()swap()gcd()toupper()tolower()floor()ceil()1. pow( ) This function helps to find the value of a number raised to a
7 min read
Passing Pointers to Functions In C++
Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any variable in the function we have to pass the address of
4 min read
C++ - Difference Between Functors and Functions
In C++, we have multiple options to operate over the data like in the case where we can use functions and functors. Although both seem to be similar in a few ways but have multiple differences between them. Let's check the differences between functions and functors in C++. What are functions? Functions are pieces of code that can be called from any
3 min read
C++ Map of Functions
Prerequisites: Functions in C++Map in C++ Maps in C++ are a very useful data structure for storing key-value pairs. A map is the best way to store where we can directly find and access the value using a key with the best time complexity. However, did you know that you can also store functions as values in a C++ map? That's right - it is possible to
5 min read
Using Non-Member Friend Functions With Vector in C++ STL
In C++, Non-member buddy functions may access a class's private members while not being members. The class definition declares them friend. Vector containers, dynamic arrays in C++ Standard Library (STL), may dynamically resize as members are added or deleted. You may need to establish a new class with a vector to utilize non-member friend methods
2 min read
String Functions In C++
A string is referred to as an array of characters. In C++, a stream/sequence of characters is stored in a char array. C++ includes the std::string class that is used to represent strings. It is one of the most fundamental datatypes in C++ and it comes with a huge set of inbuilt functions. In this article, will look at the functions of string comput
9 min read
Can Static Functions Be Virtual in C++?
In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function v
1 min read
Some interesting facts about static member functions in C++
1) static member functions do not have this pointer. For example following program fails in compilation with error "`this' is unavailable for static member functions " C/C++ Code #include<iostream> class Test { static Test * fun() { return this; // compiler error } }; int main() { getchar(); return 0; } 2) A static member function cannot be v
1 min read
Functions that cannot be overloaded in C++
In C++, following function declarations cannot be overloaded. 1) Function declarations that differ only in the return type. For example, the following program fails in compilation. C/C++ Code #include&lt;iostream&gt; int foo() { return 10; } char foo() { return 'a'; } int main() { char x = foo(); getchar(); return 0; } 2) Member function de
3 min read
Pure Functions
A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. The only result of calling a pure function is the return value. Examples of pure functions are strlen(), pow(), sqrt() etc. Examples of impure functions
2 min read
Can Virtual Functions be Inlined in C++?
Virtual functions are member functions that are declared in the base class using the keyword virtual and can be overridden by the derived class. They are used to achieve Runtime polymorphism or say late binding or dynamic binding. Inline functions are used to replace the function calling location with the definition of the inline function at compil
2 min read
Const member functions in C++
Constant member functions are those functions that are denied permission to change the values of the data members of their class. To make a member function constant, the keyword const is appended to the function prototype and also to the function definition header. Like member functions and member function arguments, the objects of a class can also
6 min read
Inline Functions in C++
C++ provides inline functions to reduce the function call overhead. An inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of the inline function call. This substitution is performed by the C++ compiler at compile tim
9 min read
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all functions cannot be provided in a base class because we don't know the implementation. Such a class is called an abstract class.For example, let Shape be a base class. We cannot provide the implementation of function draw() in Shape, but we know every derived class must have an implementation of draw(). Similarly, an
6 min read
Macros vs Functions
A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-processor, the block of code is communicated to the compiler before entering into the actual coding (main () function). A macro is defined with the pre-processor directive. Macros are pre-processed which means that all the macros would be processed before y
4 min read