tags:

views:

66

answers:

6

Is it possible to have a function that returns an array of variable size? My plan is to have the size of the returned array as the first member of the array (so ret_val[0] = # of members in ret_val).

The problem then becomes with initializing an array to the return value of that function. int moves[] = target_function() wouldn't possibly compile.

+1  A: 

You can return a pointer instead of an array:

int* moves = target_function();

But don't return a pointer to something you created on the stack as it will go out of scope when the function returns. You can dynamically allocate the array on the heap.

Mark Byers
Sorry, but I -1 bad practices. The function should return a `std::vector`.
GMan
A: 

Such array cannot be an automatic variable. It needs to be a pointer to a dynamically created array as Mark said.

Victor
More of a comment than an answer.
GMan
A: 

The short answer is that you can't return an array. You can return a pointer to dynamically allocated memory though:

int* moves = target_function();
// do stuff with moves
delete[] moves;

The target_function() will have to use new to allocate the memory.

Note that this is not ideal from a memory management point of view, because it's easy to forget to call delete[] on the returned array. Instead, consider returning a std::vector<int>.

mch
+1  A: 

I would suggest not using such hacks. There is std::vector ready for you to use. If you really want to go this way, here's the code that does what you want:

int *allocate(int size)
{
  int *res = new int[size];
  res[0] = size;
  return res;
}


// Prints "Yes, it's 42":
int *myArray = allocate(42);
if (myArray[0] == 42)
  std::cout << "Yes, it's 42!" << std::endl;
dark_charlie
+1  A: 

Usually you would use a pointer to an dynamically allocated array:

int* target_function() {
  int result* = new int[123];
  result[0] = 123;
  return result;
}

int *moves = target_function();
std::cout << moves[0] << " moves" << std::endl;

That being said, generally it is more practical and less error prone to use a standard library container like std::vector<int> instead. In C++ this is basically always the better choice than a raw array.

sth
+2  A: 

Every one is telling you to use a vector, but nobody is showing you how to do that. Here's how:

#include <vector>

std::vector<int> target_function(int size)
{
    std::vector<int> v(size);
    v[0] = size;
    return v;
}

int main()
{
    std::vector<int> moves = target_function( my_favorite_int );
}
PigBen
Thank you, +1 for just suggesting a vector instead of this beat-around-the-bush crap. What's the point in saying "Here's the code. Oh by the way, that's bad code don't use it."?
GMan