- Trending Categories
- 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
How to return an array from a function in C++?
C++ does not return entire array but it can return pointer to an array. Outside the function, address of local variable cannot be returned. By making local variable static, it can return the address of local variable.
The following is the syntax to return a pointer.
int * function_name() { body }
Here,
function_name − The name of function given by user.
The following is an example to return an array from a function.
Example
#include <iostream> using namespace std; int * ret() { static int x[3]; for(int i=0 ; i<5 ; i++) { cout << " " <<&x[i]; } return x; } int main() { ret(); return 0; }
Output
0x601180 0x601184 0x601188 0x60118c 0x601190
In the above program, a function ret() is created and it is returning an array. A static int type array is declared and addresses of allocated memory blocks are printed.
int * ret() { static int x[3]; for(int i=0 ; i<5 ; i++) { cout << " " <<&x[i]; } return x; }
In the main() function, the function ret() is called −
ret();
Advertisements