8
Contributors
8
Replies
9
Views
8 Years
Discussion Span
Last Post by ddanbe
0

can a function return array?

if a function has array as parameter ,
the array be pass by reference,
so if you modifying this array in this function the origin array is modifying without need the return ;

0

As stated, not directly.

But if you really, really think you need to do so, you can wrap an array inside a struct, which can be returned. It's not necessarily a wise thing to do.

Example

#include <iostream>
using namespace std;

struct foo
{
	int arr[5];
};

foo bad( )
{
	foo a;
	int k;

	for( k = 0; k < 5; k++ )
		a.arr[k] = k;

	return a;
}

int main()
{
    int i;

	foo my_foo;

	my_foo = bad( );

	for( i = 0; i < 5; i++ )
		cout << my_foo.arr[i] << endl;

	return 0;
}

(donning flak jacket now!)

1

Another way:

#include <iostream>

template<typename t, size_t s>
struct Array {
  t buffer[s];

  operator t*() {
    return buffer;
  }
};

Array<int, 5> getNums() {
  Array<int, 5> nums;
  nums[0] = 0;
  nums[1] = 1;
  nums[2] = 2;
  nums[3] = 3;
  nums[4] = 4;
  return nums;
}

int main() {
  Array<int, 5> nums = getNums();
}
Votes + Comments
elegantly minimal
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.