Initializing an array of unknown size

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

Then there is a problem with initializing the array with the return value of this function. int moves[] = target_function()will not compile.

+3
source share
6 answers

Everyone tells you to use a vector, but nobody shows you how to do it. 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 );
}
+7
source

You can return a pointer instead of an array:

int* moves = target_function();

, , . .

+2

. std::vector . , , , :

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


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

:

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

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

, , std::vector<int>. ++ , .

+1

. , .

0

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

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

To allocate memory, <<21> must use new.

Note that this is not ideal in terms of memory management, because it is easy to forget to call delete[]in the returned array. Instead, consider returning std::vector<int>.

0
source

Source: https://habr.com/ru/post/1772281/


All Articles