- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Passing an array to a C++ function
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
Advertisements