
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to return local array from a C++ function?
A local array cannot be directly returned from a C++ function as it may not exist in memory after the function call. A way to resolve this is to use a static array in the function. As the lifetime of the static array is the whole program, it can easily be returned from a C++ function without the above problem.
A program that demonstrates this is given as follows.
Example
#include <iostream> using namespace std; int *retArray() { static int arr[10]; for(int i = 0; i<10; i++) { arr[i] = i+1; } return arr; } int main() { int *ptr = retArray(); cout <<"The array elements are: "; for(int i = 0; i<10; i++) { cout<< ptr[i] <<" "; } return 0; }
Output
The output of the above program is as follows.
The array elements are: 1 2 3 4 5 6 7 8 9 10
Now let us understand the above program.
In the function retArray(), a static array arr is defined. Then a for loop is used to initialize this array. Finally array arr is returned. The code snippet that shows this is as follows.
int *retArray() { static int arr[10]; for(int i = 0; i<10; i++) { arr[i] = i+1; } return arr; }
In the main() function, the function retArray() is called and ptr points to the start of the array arr. The array elements are displayed using a for loop. The code snippet that shows this is as follows.
int main() { int *ptr = retArray(); cout <<"The array elements are: "; for(int i = 0; i<10; i++) { cout<< ptr[i] <<" "; } return 0; }
- Related Articles
- How to return a local array from a C/C++ function
- How to return an array from a function in C++?
- Haskell Program to return an array from the function
- How to return a value from a JavaScript function?
- How to return a string from a JavaScript function?
- How to access a local variable from a different function using C++ pointers?
- How to return an object from a JavaScript function?
- How to return void from Python function?
- How to return table from MySQL function?
- How to return a json object from a Python function?
- How to return an object from a function in Python?
- How to return a matplotlib.figure.Figure object from Pandas plot function?
- How to return an array from a method in Java?
- How to return a JSON object from a Python function in Tkinter?
- How to return variable value from jQuery event function?
