There is the following task: initially we do not know the size of the array that we need to process, we need to write a function that would work with a dynamic array and return the processed array of strings.

string fucntion(string* text[]) { string* text_out=new string[]; /* *do something */ return text_out; } 

How can I return an array of strings?

  • four
    and std::vector<std::string> cannot be used? - KoVadim
  • 2
    @KoVadim and if not, then I would like to hear the "why." And it would be good that it was not "so the teacher said." - αλεχολυτ
  • @KoVadim, you can, in principle, I have no restrictions whatsoever. And then how to return the vector? - engineer_7
  • I will explain the previous comment, after replacing the type of the function, my ide highlighted the type of function i.e. vector<string> (){ } as an error, in connection with which I assumed that the type of the function cannot be declared as such. Now everything is ok. - engineer_7

1 answer 1

A strange mixture of French and Nizhny Novgorod - an array of C and C ++ strings.

Since the array is converted to a pointer to the first element, simply return a pointer:

 string* fucntion(string* text[]) { int N = 20; // Количество элементов массива string* text_out=new string[N]; /* *do something */ return text_out; } 

But look, how much trouble: you need not to forget to free up the memory later, when you return, you do not return the number of elements, and you don’t recognize it by the pointer. Are these troubles worth giving up the vector for their sake?

Much easier like this:

 vector<string> fucntion(/* что там нужно */) { vector<string> array; /* *do something */ return array; } 

And no problems!