#Best way to return array in cpp?

10 messages · Page 1 of 1 (latest)

glass ingot
#

I want to make a function that creates an new array and returns it

What is the best way to do it?

I could use:

int* createArray(){
int *a = new int[5];
return a;
}

but then I only have a pointer to first element of array and I don't know the size. So I can't iterate through it? Do I need to create a struct to contains pointer to first element and size?

dusky schoonerBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

proud crater
#

return a std::tuple

#

unless you’re not using C++

#

in which case ask #1013104018739974194

glass ingot
#

why can we create an array in c++ (int a[n]), but not return one?

lament glen
#

because of C++'s C legacy

#

why not create a std::vector? that should be your default "array" in C++ unless you have some good reason to do otherwise

glass ingot
#

!solved

dusky schoonerBOT
#

Thank you and let us know if you have any more questions!