Advertisement

how can i return an array in c++

Started by June 03, 2001 12:52 AM
4 comments, last by thuned 23 years, 8 months ago
? life is unfair, take advantage of it. UNMB2 - if the link doesn''t work, try clicking it
life is unfair, take advantage of it.UNMB2 - if the link doesn't work, try clicking it :)
arrays are automatilcally passed by reference.. however you change it in the function, changes the original instance of the array...
Advertisement
But you can copy the array within the function and return a reference to that instead.
Wouldn''t it be easier to return the array using an STL vector?

std::vector MyFunction(some arguments)
{
// do something with arguments and put results in
// a std::vector instance.

std::vector workingset;

return workingset;
}

Obviously this requires a copy of each ''node'' present in the vector ''workingset'' but there are ways around that.

You could pass a vector class to MyFunction by reference and then have the function fill the vector.

Just a thought.

Dire Wolf
www.digitalfiends.com
[email=direwolf@digitalfiends.com]Dire Wolf[/email]
www.digitalfiends.com
Actually on second thought, if you want to use simple data types and avoid std::vector you could also use std::pair.

std::pair MyFunction(some arguments)
{
return std::make_pair(new char[20], 20);
}

The first position pair::first represents the pointer to the array and pair::second represents the length of the array.

Maybe if you provide us with an example of why you want to return an array it might make it easier to help you



Dire Wolf
www.digitalfiends.com

[email=direwolf@digitalfiends.com]Dire Wolf[/email]
www.digitalfiends.com
Just return a pointer to the first element of the array. If you also need to return the number of elements in the array then either wrap the array in a class like:

class ArraywithSize
{
int* Array;
int nElements;
~Arraywithsize;
};

and return a pointer to an ArraywithSize object. Or use some value to mark the end of the array (like \0 for char*). Or pass in a pointer to an int and fill the int with the length of the array.

This topic is closed to new replies.

Advertisement