joi, 17 februarie 2011

Passing an array to a function in C++

In C++ you if you want to modify an array inside a function, you should not return a pointer to it from within the function as this pointer will be out of scope when the function execution ends. You need to make sure that you allocate the array before passing it as a parameter:

int* buffer = new int[ BUFFER_SIZE];

arrayProcessing( buffer, BUFFER_SIZE );
#ifdef _DEBUG
DisplayBuffer( );
#endif

where arrayProcessing is defined like this:

int arrayProcessing( int* buffer, int size )
{
// TODO: modify elements of buffer.
}