Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an array from a function?

How can I return an array from a method, and how must I declare it?

int[] test(void); // ?? 
like image 654
ewggwegw Avatar asked Nov 24 '10 07:11

ewggwegw


People also ask

Can we return an array from a function in Python?

Yes. Only common similar language with 1 based lists is Lua. Those Python examples are not strictly arrays, but I suppose by array you mean a list, string or similar. The actual array types that there are for Python are also 0 based.

How do you return an array from a function in JavaScript?

JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object. Use destructuring assignment syntax to unpack values from the array, or properties from objects.

Can we return array in Java function?

We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.


1 Answers

int* test();

but it would be "more C++" to use vectors:

std::vector< int > test();

EDIT
I'll clarify some point. Since you mentioned C++, I'll go with new[] and delete[] operators, but it's the same with malloc/free.

In the first case, you'll write something like:

int* test() {     return new int[size_needed]; } 

but it's not a nice idea because your function's client doesn't really know the size of the array you are returning, although the client can safely deallocate it with a call to delete[].

int* theArray = test(); for (size_t i; i < ???; ++i) { // I don't know what is the array size!     // ... } delete[] theArray; // ok. 

A better signature would be this one:

int* test(size_t& arraySize) {     array_size = 10;     return new int[array_size]; } 

And your client code would now be:

size_t theSize = 0; int* theArray = test(theSize); for (size_t i; i < theSize; ++i) { // now I can safely iterate the array     // ... } delete[] theArray; // still ok. 

Since this is C++, std::vector<T> is a widely-used solution:

std::vector<int> test() {     std::vector<int> vector(10);     return vector; } 

Now you don't have to call delete[], since it will be handled by the object, and you can safely iterate it with:

std::vector<int> v = test(); std::vector<int>::iterator it = v.begin(); for (; it != v.end(); ++it) {    // do your things } 

which is easier and safer.

like image 62
Simone Avatar answered Sep 27 '22 23:09

Simone