Suppose I have an array
int arr[] = {...};
arr = function(arr);
I have the function as
int& function(int arr[])
{
//
int& function(int arr[])
In this function arr is a pointer, and there's no way to turn it back to an array again. It's the same as
int& function(int* arr)
int arr[] = {...};
arr = function(arr);
Assuming the function managed to return a reference to array, this still wouldn't work. You can't assign to an array. At best you could bind the result to a "reference of an array of X ints" (using a typedef because the syntax would get very ugly otherwise):
typedef int ten_ints[10];
ten_ints& foo(ten_ints& arr)
{
//..
return arr;
}
int main()
{
int arr[10];
ten_ints& arr_ref = foo(arr);
}
However, it is completely unclear what the code in your question is supposed to achieve. Any changes you make to the array in function will be visible to the caller, so there's no reason to try to return the array or assign it back to the original array.
If you want a fixed size array that you can assign to and pass by value (with the contents being copied), there's std::tr1::array
(or boost::array
). std::vector
is also an option, but that is a dynamic array, so not an exact equivalent.
Following works and doesn't seem messy or mis-understandable!
int* returnarray(int a[])
{
for (unsigned int i = 0; i < 3; i++)
{
a[i] *= 2;
}
return a;
}
int main(int argc, char* argv[])
{
int arr[3] = {1,2,3};
int* p = returnarray(arr);
for (unsigned int i = 0; i < 3; i++)
{
cout << "p[" << i << "] = " << p[i] << endl;
}
cin.get();
return 0;
}
You cannot assign an array to another array in C++. Consider using a STL vector: http://www.cplusplus.com/reference/stl/vector/
Well, arr is compatible with int*
, not int&
. Your code won't compile. Perhaps you wanted return arr[0]
?
As others said, there are better options like STL containers and the most interesting question is why you need to return the array to a function that already has it in scope.
That being said, you can't pass or return arrays by value and need to avoid the array decaying to a pointer (see e.g. here), either by using pointers or references to it:
int (&f(int (&arr)[3]))[3]
{
return arr;
}
If you don't want to hard-code the size, you can use template functions:
template<size_t n>
int (&f(int (&arr)[n]))[n]
{
return arr;
}