Re: using function arguments in other arguments
* Lynn McGuire:
int myFunction (int ncp, double myArray [ncp] [2]);
This is the way you pass arrays to a function, passing the name of the
array(while array name is automatically converted to a pointer to the
first element during the function call) and the size of the array, but
what is your aim with these prototypes? Better suggestions can come
out if readers know the ultimate goal, my humble idea...
We do this all the time in fortran. My intent here
is to know the size of the array being passed to the
function from the caller. Otherwise, my function does
not have a clue as to the first limit of the array.
In C++ you have essentially two choices: that the array size is known at compile
time, or that it's only known at run time.
A function that works with the caller having run time knowledge of array size
can also work with caller having compile time knowledge (obviously), but you can
also devise a function that requires caller to have compile time knowledge.
To show the latter first:
template< size_t N >
void foo( double const (&myArray)[N] )
{
for( size_t i = 0; i < N; ++i ) { bar( myArray[i] ); }
}
int main()
{
static double const a[] = {1.0, 2.0, 3.0};
foo( a );
}
For run-time size you'd use std::vector or some other library class,
void foo( std::vector<double> const& myArray )
{
for( size_t i = 0; i < myArray.size(); ++i ) { bar( myArray[i] ); }
}
int main( int n, char** )
{
static std::vector<double> a( n );
foo( a );
}
Any decent C++ textbook will explain this.
It's probably a good idea to invest in a textbook.
Cheers & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?