Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ return array from function [duplicate]

I need to read in an array to my function, extract the data, and then return an array from the function.

The array will only ever hold 2 values.

This is what I want to do in concept:

int myfunction(int my_array[1])
{
    int f_array[1];
    f_array[0] = my_array[0];
    f_array[1] = my_array[1];

    // modify f_array some more

    return f_array;
}

I've read up about pointers etc but have got very confused and would appreciate a really basic example of how best to approach this!

Thanks!

like image 426
user1055774 Avatar asked Jan 05 '12 15:01

user1055774


1 Answers

You can't return n builtin array in c++.

If you are new to c++ and get confused about pointers you really don't want to use arrays (at least not builtin arrays). Use std::vector<int> instead, or if you only ever have a certain number of elements and want to express that (and really need the better performance) use boost::array<int, N>.(or even std::array<int, N>, if you program in C++11 (if you don't know whether or not you program in C++11 chances are that you don't). For example:

std::vector<int> myfunction(const std::vector<int>& my_array) {
  std::vector<int> f_array;
  for(int i = 0; i < my_array.size(); ++i)
    f_array.push_back(my_array[i]);
  return f_array;
}

boost::array<int, 2> myfunction(const boost::array<int, 2>& my_array) {
  boost::array<int, 2> f_array;
  f_array[0] = my_array[0];
  f_array[1] = my_array[1];
  return f_array;
}

You can then make your copying code simpler (look up the constructors and memberfunctions of whatever class you decide to use, as well as STL algorithms). Example:

std::vector<int> myfunction(const std::vector<int>& my_array) {
  std::vector<int> f_array(m_array);
  ...
  return f_array;
}

As another point your code has a bug in it: you define my_array as int my_array[1], meaning its an array with one element, but you access two elements (my_array[0] and my_array[1]), the access to my_array[1] is out of bounds (int foo[N] has place for N items, starting at index 0 and going to index N-1). I assume you really mean int my_array[2].

like image 195
Grizzly Avatar answered Oct 21 '22 03:10

Grizzly