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 开发者_JAVA百科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.
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 );
}
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.
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;
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.
Such array cannot be an automatic variable. It needs to be a pointer to a dynamically created array as Mark said.
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>
.
精彩评论