Suppose I have an array
int arr[] = {...};
arr = function(arr);
I have the function as
int& function(int arr[])
{
//rest of the code
return arr;
}
What mistake am I making over here??
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
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):
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(orboost::array).std::vectoris also an option, but that is a dynamic array, so not an exact equivalent.