Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return an array in c++

Tags:

c++

arrays

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??

like image 725
manugupt1 Avatar asked Feb 20 '10 13:02

manugupt1


People also ask

Can you return an array in C?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

What is return in array?

Keypoint 1: Method returning the array must have the return type as an array of the same data type as that of the array being returned. The return type may be the usual Integer, Double, Character, String, or user-defined class objects as well.

Can I return a function in C?

Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.


1 Answers

 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.

like image 121
UncleBens Avatar answered Oct 08 '22 01:10

UncleBens