Tuesday, 26 September 2017

How to pass a multidimensional array to a function without inner dimension in c++?




I was wondering if there was a way to say pass this for example double MyArray[][2] = {{0.1,0.8},{0.4,0.6}} to a function like this void MyFunction(double myArray[][]);, without saying this void MyFunction(double myArray[][2]);. I need this because I want my function to be able to handle arrays with different inner dimensions for example: double MyArray[][3] = {{0.1,0.8},{0.4,0.6},{0.3,0.9}}. To pass this to a function as far as I know I would have to change MyFunctions's parameters to MyFunction(myArray[][3]);. From what I have read I don't know if this is possible, so if it is not then is there some other way of doing this?


Answer



You can pass an arbitrary 2d array by reference if you could change MyFunction to:




template
void MyFunction(double (&myArray)[N][M]) {
// ...
}


This way you would also have dimensions of the array.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...