Passing an Array Safely

closed account (zb0S216C)
Is there a another way to pass an array safely in a function? I normally do it like this:
1
2
3
4
5
6
7
void Function( int PassedArray[ ] = NULL )
{
   if( PassedArray == NULL )
   {
       // Handle the NULL array here...
   }
}

To be honest, I find that checking for NULL all the time gets on my nerves.
Last edited on
No. Every time you pass an array to a function, a pointer to its initial element is passed. So that you will have to handle that argument as a pointer. To be more safe you could use a STL Vector instead of built in array
Last edited on
closed account (zb0S216C)
I thought about using a template array already, sajithshn. It's pretty much based on the auto_ptr or smart pointer class. I've started replacing ordinary arrays with my own. I no longer use ordinary arrays unless I have to.
1
2
int NormalArray[ 3 ];                     // Ordinary array.
FixedArray < int > MyFixedArray( 3, 0 );  // My version of the array. 


I've got two array class, both are templates. The first one is allocated from the heap and released on destruction. The second is placed on the stack. Both classes have member functions that perform operations on the array it holds, such as swapping to values, releasing the array at any time( heap version only ) as well as re-building the array with different values( heap version only ).
Last edited on
If your arrays are fixed length, then this works:

1
2
3
4
5
6
7
8
9
10
11
template< typename T, size_t N >
void print( T (&array)[ N ] )
{
    for( size_t i = 0; i < N; ++i )
        std::cout << "array[" << i << "] = " << array[ i ] << std::endl;
}

int main() {
    int a[ 5 ] = { 1, 2, 3, 4, 5 };
    print( a );
}


Alternatively, there is boost::array<T, N> which provides you iterators, begin(), end(), size() etc for your array.

As a second alternative, you can write algorithms that accept iterators:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template< typename InputIter >
void print( InputIter first, InputIter last )
{
    for( ; first != last; ++first )
        std::cout << *first << std::endl;
}

template< typename T, size_t N >
size_t a_size( T (&)[ N ] )
    { return N; }

int main() {
    boost::array< int, 5 > a = { { 1, 2, 3, 4, 5 } };
    int b[ 5 ] = { 6, 7, 8, 9, 10 };
    print( a.begin(), a.end() );
    print( b, b + a_size( b ) );
}


closed account (zb0S216C)
Thanks for the reply, jsmith. Although I don't use boost. Note that you've used template methods when I use template classes.
There's no need for boost. Check your implementation for std::array or tr1::array.
Topic archived. No new replies allowed.