passing 2D arrays to functions expecting a vector


junderwood
07-01-2003, 08:23 AM
Hi

[this question refers specifically to the C version of NR, and possibly the C++ version, though I've never used that]

Am I correct in thinking that a function requiring a vector input (eg. the ODE solvers) could actually be passed a 2D matrix (as allocated using the funcs in nrutil.c) by passing the address &array[0][0] since the 2D arrays are contiguous chunks of memory? Of course the number of vector elements would need to be calculated correctly. I know that for 0 offset arrays and vectors this is true, I'm just wondering if the unti offset for 2D arrays destroys the contiguous nature of the memory area?

Thanks,
Jonathan

Bill Press
07-05-2003, 09:41 PM
Hello, Jonathan.
This response refers to NR in C, not to NR in C++.
The answer to your question is basically "yes", but with one caveat.
If you allocate a matrix using the **matrix(), **dmatrix(), or **imatrix() routines in Appendix B of NR in C, then the storage is allocated by a single
malloc((size_t)((nrow*ncol+NR_END)*sizeof(--whatever--)))
All the nrow*ncol data values are in the addresses &array[nrl][nrc] and sequentially. Note this is not necessarily &array[0][0] unless **matrix has been created with values for zero offset. If it is unit offset, then the address of the first data point is &array[1][1], but you can still do what you want to do.
Hope this helps!
Cheers,
Bill P.