Suppose I have an array
int arr[] = {...};
arr = function(arr);
I have the function as
int& function(int arr[])
{
//
You're returning a reference to an int, not a reference to an array.
You want :
(int*)& function(int arr[])
{
/// rest of the code
return arr;
}
That said, as others already said, that's not good practice.
I think your best bet is to return it as a pointer to an array. Here is an example:
{
...
int newLength = 0;
int* arr2 = ChangeArray(arr, length, newLength);
...
delete[] arr2;
}
int* ChangeArray(int arr[], int length, int& newLength)
{
// reversing the number - just an example
int* newArr = new int[length];
for(int i = 0; i < length; i++)
{
newArr[i] = arr[length-i-1];
newLength++;
}
return newArr;
}
Use std:: vector like this.
std::vector<int> function(const std::vector<int>& arr)
{
return arr;
}
An array like
int arr[] = {...};
is not useful to be returned from a function because its not able to copy itself.
if not necessary, don't use it. you can just pass a reference of an array, such as:
void foo(std::vector<int> &v) {
for (int i = 0; i < 10; ++ i) {
v.push_back(i);
}
}
if you use:
std::vector<int> foo() {
std::vector<int> v;
for (int i = 0; i < 10; ++ i)
v.push_back(i);
return v;
}
there'll be a copy process of the container, the cost is expensive.
FYI: NRVO maybe eliminate the cost
The semantics of array passing and return can be quite confusing. Use a std::vector instead.