Re: Q: Prototype & function calls for multi-dimensional arrays. Best
way?
* James Tursa:
MVC 8.0
Windows XP
I would like to use multidimensional arrays in a function call. This
method works:
//-------------------------------------------------------------------------
void fun(double *d, int m, int n);
extern int main(void)
Don't do 'extern' there.
Also, although formally allowed, 'void' as indication of no arguments is
C'ism, best a'voided. In C++ no arguments is indicated by no arguments.
{
double a[2][3] = {1.0,2.0,3.0,4.0,5.0,6.0};
double b[3][4] =
{1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0};
fun( (double *) a, 2 ,3);
fun( (double *) b ,3, 4);
}
void fun(double *d, int m, int n)
{
// code here to work with d as an m x n matrix.
return;
}
//----------------------------------------------------------------------
But what I would really like to do is avoid the cast in the fun call
(mainly for readability and ease of programming). I.e., I would like
to change these lines:
fun((double *)a,2,3);
fun((double *)b,3,4);
into these lines:
fun(a,2,3);
fun(b,3,4);
and have the function interface be able to handle it. Is there a way
to set up the function interface to do this?
A great many ways.
For the particular example above the simplest would probably be a
templated function taking the matrix by reference,
template< size_t N, size_t M >
void fun( double (&d)[N][M] ) { ... }
But if you're going to matrices and are confounded by this problem, I
suggest you use some ready-made matrix library.
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?