Different ways to pass Array into Function in C++

There are many ways in which you can pass array into function. I’ve discussed 3 different ways to do this.

How programs works:

1-  Declare array of size 10
2- Initialize it using for loop
3- Calling “UpdateArray” function and passing array as argument
4- Take squares of all values and update it
5- Display final result in main function

FIRST WAY:

As we know array name is a constant pointer if we can get the this pointer we can access all values of array.
declaring  array in function parameter
Prototype: void  UpdateArray(int array[] );
 

CODE to pass Array into Function in C++:

You can also execute this code on our online compiler.

#include <iostream>
using namespace std;
void UpdateArray(int array[])
{
for(int i=0;i<=9;i++)
array[i]=array[i]*array[i];
}
int main()
{
int array[10];
for(int i=0;i<=9;i++)
array[i]=i+1;
UpdateArray(array);
// Updated Values of Array
for(int i=0;i<=9;i++)
cout<<array[i]<<endl;
return 0;
}

 

SECOND WAY:

Declaring an integer pointer in function parameter
This pointer will receive arrays name(constant pointer) and we can access all values and update too.
Prototype: void  UpdateArray(int *array );
 

CODE to pass Array into Function in C++:

You can also execute this code on our online compiler.

#include <iostream>
using namespace std;
void UpdateArray(int *array)
{
for(int i=0;i<=9;i++)
array[i]=array[i]*array[i];
}
int main()
{
int array[10];
for(int i=0;i<=9;i++)
array[i]=i+1;
UpdateArray(array);
// Updated Values of Array
for(int i=0;i<=9;i++)
cout<<array[i]<<endl;
return 0;
}

 

 
THIRD WAY:

In this way we pass two arguments one is arrays name and second is its size.
In function receiving parameters we declares an array or integer pointer (your choice) to receive address of array and another integer variable size which contains the size of array.Prototype:  void  UpdateArray(int *array, int size );

CODE to pass Array into Function in C++:

You can also execute this code on our online compiler.

#include <iostream>
using namespace std;
void UpdateArray(int *array, int size)
{
for(int i=0;i<size;i++)
array[i]=array[i]*array[i];
}
int main()
{
int array[10];
for(int i=0;i<=9;i++)
array[i]=i+1;
UpdateArray(array,10);
// Updated Values of Array
for(int i=0;i<=9;i++)
cout<<array[i]<<endl;
return 0;
}

 

Leave a Comment