Function Cannot Return Array Type
How to Return a Local Array From a C++ Function?
Here, we will build a C++ program to return a local array from a function. And will come up beyond the correct style of returning an assortment from a office using 3 approaches i.e.
- Using Dynamically Allocated Array
- Using Static Array
- Using Struct
C++
#include <iostream>
using
namespace
std;
int
* fun()
{
int
arr[100];
arr[0] = 10;
arr[ane] = 20;
return
arr;
}
int
main()
{
int
* ptr = fun();
cout << ptr[0] <<
" "
<< ptr[ane];
render
0;
}
Warning:
In function 'int* fun()': half dozen:eight: warning: address of local variable 'arr' returned [-Wreturn-local-addr] int arr[100]; ^
The higher up program is Incorrect. Information technology may produce values of 10 or 20 as output or may produce garbage values or may crash. The trouble is, that we return the address of a local variable which is not advised as local variables may non exist in retention after the part telephone call is over.
Post-obit are some correct ways of returning an assortment
1. Using Dynamically Allocated Assortment
Dynamically allocated retention (allocated using new or malloc()) remains there until we delete it using the delete or gratis(). So we tin create a dynamically allocated assortment and we tin delete it once nosotros come up out of the function.
Case:
C++
#include <iostream>
using
namespace
std;
int
* fun()
{
int
* arr =
new
int
[100];
arr[0] = 10;
arr[ane] = 20;
render
arr;
}
int
main()
{
int
* ptr = fun();
cout << ptr[0] <<
" "
<< ptr[1];
delete
[] ptr;
return
0;
}
ii. Using static Array
The lifetime of a static variable is throughout the program. So we can always create a local static array and return information technology.
Example:
C++
#include <iostream>
using
namespace
std;
int
* fun()
{
static
int
arr[100];
arr[0] = 10;
arr[1] = 20;
return
arr;
}
int
main()
{
int
* ptr = fun();
cout << ptr[0] <<
" "
<< ptr[1];
return
0;
}
3. Using struct
Nosotros tin can wrap the array in a structure/class and return an instance of the struct/course. The reason for this work is, that the array of members of structures is deeply copied. In the below program deep copy happens when we returned case is copied in master.
Example:
C++
#include <iostream>
using
namespace
std;
struct
arrWrap {
int
arr[100];
};
struct
arrWrap fun()
{
struct
arrWrap x;
x.arr[0] = 10;
x.arr[1] = 20;
return
10;
}
int
main()
{
struct
arrWrap 10 = fun();
cout << x.arr[0] <<
" "
<< 10.arr[i];
return
0;
}
Function Cannot Return Array Type,
Source: https://www.geeksforgeeks.org/how-to-return-a-local-array-from-a-cpp-function/
Posted by: mossgess1946.blogspot.com
0 Response to "Function Cannot Return Array Type"
Post a Comment