The problem with an array is that you must also know the size of the array. Hence, an STL container like the std::vector is nice, since it does all the bookkeepping for you.
If you must, however, you can also just use one of the following C methods:
Fill an existing array
1 2 3 4 5 6
void myfn( int* a, unsigned alen )
{
// Fill the array a[ alen ] here.
// In this case, the array a already exists with alen elements.
// This function only fills it.
}
struct myarray
{
int* a;
unsigned length;
// Useful C++ stuff follows
myarray( unsigned len ):
a( len ? (newint[ len ]) : NULL ),
length( len )
{ }
~myarray()
{
if (a) delete [] a;
}
int& operator [] ( unsigned n )
{
return a[ n ];
}
constint& operator [] ( unsigned n ) const
{
return a[ n ];
}
};
myarray myfn()
{
myarray a( 10 );
a[ 0 ] = 42;
...
return a;
}
1 2 3 4
myarray xs = myfn();
for (unsigned n = 0; n < xs.length; n++)
cout << xs[ n ] << endl;
// no need to delete anything here... the destructor does it for you...