Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arrays as a reference

In C++ how can I pass an array as a reference when I don't know the size at compile time? So far, I found out that the only way to make it work is to use something like

const double( &numbers ) [size]

but it means that I need to know the size of the array at compile time, thus I cannot use it in an external function.

My questions are:

  1. If I don't pass an array as a ( const double( &numbers ) [length] ), because for example I don't know its size, how do I make sure that it doesn't get copied, but it is referenced?
  2. If I pass an array like in the above example, ( double array[] ) is it referenced or is it copied?
like image 251
hyperknot Avatar asked Oct 26 '11 06:10

hyperknot


1 Answers

The other answers are great, but no one mention using templates to handle this. You should still make your function take a pointer and a size, but templates can fill that automatically for you:

void f( double const numbers[], std::size_t length )
{ ... }

template< std::size_t Length >
void f( double const (&numbers)[ Length ] )
{
    return f( numbers, Length );
}
like image 163
K-ballo Avatar answered Oct 12 '22 22:10

K-ballo