Passing an array to a C++ function

C++Server Side ProgrammingProgramming

C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.

If you want to pass a single-dimension array as an argument in a function, you would have to declare function formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received.

There are 3 ways to pass an array to a function −

  • Formal parameters as a pointer

void myFunction(int *param) {
   // Do something
}
  • Formal parameters as a sized array

void myFunction(int param[10]) {
   // Do something
}

  • Formal parameters as an unsized array

void myFunction(int param[]) {
   // Do something
}

Example

You can use it as follows −

#include<iostream>
using namespace std;
void arrayAccept(int arr[]) {
   cout << "first element is: " << arr[0];
}
int main() {
   int arr[2];
   arr[0] = 0;
   arr[1] = 1;
   arrayAccept(arr);
   return 0;
}

Output

This will give the output −

first element of array is 0
raja
Published on 28-Feb-2018 09:57:30
Advertisements