manugupt1
manugupt1

Reputation: 2437

Return an array in c++

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

Upvotes: 8

Views: 12115

Answers (11)

Rajendra Uppal
Rajendra Uppal

Reputation: 19914

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;
}

Upvotes: 3

Fadrian Sudaman
Fadrian Sudaman

Reputation: 6465

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;
}

Upvotes: 2

UncleBens
UncleBens

Reputation: 41331

 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.

Upvotes: 8

ddh
ddh

Reputation: 235

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

Upvotes: 0

Georg Fritzsche
Georg Fritzsche

Reputation: 98984

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;
}

Upvotes: 8

Totonga
Totonga

Reputation: 4366

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.

Upvotes: 0

IVlad
IVlad

Reputation: 43477

You cannot assign an array to another array in C++. Consider using a STL vector: http://www.cplusplus.com/reference/stl/vector/

Upvotes: 0

Vlad
Vlad

Reputation: 35584

Well, arr is compatible with int*, not int&. Your code won't compile. Perhaps you wanted return arr[0]?

Upvotes: 0

Klaim
Klaim

Reputation: 69672

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.

Upvotes: 3

anon
anon

Reputation:

The semantics of array passing and return can be quite confusing. Use a std::vector instead.

Upvotes: 4

Patrick
Patrick

Reputation: 23619

  • An array as argument is actually a pointer. Arrays are automatically 'casted' to pointers if given as argument
  • You can't assign an array to another array in C/C++. You will have to use a memcpy or loop to copy the values.
  • If function changes the arr argument, it actually changes the value of the arr variable given by the caller. Again because the array is actually a pointer. So in the caller arr is assigned to arr, which is useless here.

Upvotes: 1

Related Questions