When a program exits a function all the local variables (including the arrays you declared inside) on the stack are popped and are no longer accessible outside the function. Like Follows:
(Does not work)
void func1(){
int x[3]={1,2,3};
}
int main(){
func1()
cout<<x[1];
return 0;
}
Now your second bet would be to somehow return the array, which can be done in following ways:
1. Since C++ does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.
(Works)
int * func( ) {
static int x[3]={1,2,3};
return r;
}
int main () {
// a pointer to an int.
int *x;
x = func();
cout<<x[1];
return 0;
}
2. Another way is to pass an pointer as an argument to a function and pass the array to the variable.
(Does Not Work)
void func(int *ptr){
int x[3]={1,2,3};
ptr=x;
}
int main{
int *ptr;
cout<<ptr[1];
retrun 0;
}
This does not work since array declared inside func is local variable and gets destroyed after program exits function, that's why we have to declare the array dynamically
(Does Not Works)
void func(int *ptr){
int *x{ new int[3]{1,2,3 } };
ptr=x;
}
int main(){
int *ptr;
func(ptr);
cout<<ptr[1];
return 0;
}
Even this didn't work that's because if a pointer is passed to a function as a parameter and tried to be modified then the changes made to the pointer does not reflects back outside that function. This is because only a copy of the pointer is passed to the function. The above problem can be resolved by passing the address of the pointer to the function instead of a copy of the actual function. For this, the function parameter should accept a “pointer to pointer” as shown in the below program:
(Works, Pointer to pointer)
#include<bits/stdc++.h>
using namespace std;
void func(int **ptr){
int *x{ new int[3]{1,2,3 } };
//cout<<*ptr<<endl;
//cout<<ptr<<endl;
*ptr=x;
//cout<<ptr<<endl;
//cout<<x<<endl;
}
int main(){
int *ptr;
func(&ptr);
cout<<ptr[1]<<endl;
return 0;
}
Or by passing reference allows called function to modify a local variable of the caller function. For example, consider the following example program where fun() is able to modify local variable x of main().
(Works, Reference to pointer)
#include<bits/stdc++.h>
using namespace std;
void func(int *&ptr){
int *x{ new int[3]{1,2,3 } };
//cout<<ptr<<endl;
ptr=x;
//cout<<ptr<<endl;
//cout<<x<<endl;
}
int main(){
int *ptr;
func(ptr);
cout<<ptr[1]<<endl;
return 0;
}