There are many ways to return local variables from a function in C++, but why do some work and others don't? Like, I have provided two cases:
Case 1:
int* fun1()
{
int x = 20;
int* ptr = &x;
return ptr;
}
int main()
{
int* arr = fun1();
cout << *arr;
return 0;
}
Case 2:
int* fun2()
{
int arr[100];
arr[0] = 10;
arr[1] = 20;
return arr;
}
int main()
{
int* ptr = fun2();
cout << ptr[0] << " " << ptr[1];
return 0;
}
Here both ptr
variable from fun1()
{case-1} and arr[]
from fun2()
{case-2} are local variables to their respective functions. So, why in case-1 does main()
print the returned value from fun1()
fine, but in case-2 when printing the return value it gives a segmentation fault?
Moreover, what can be a better alternative in both cases?