0

How can i pass a generic multidimensional array to a function?

Whenever I do that the compiler says that multidimensional arrays should have predefined dimensions. I have to create a generic solution that could adapt to every 2D array I give it, indipendently from it's size. I want a solution that doesn't imply vectors. Thanks :)

28th Jul 2018, 12:30 PM
Lorenzo Romeo
Lorenzo Romeo - avatar
4 Antworten
+ 3
In C++ passing multidimensional array requires all the dimensions to be defined, except for the first, here's an example for passing a 3x5 array: #include <iostream> int sumArray(int arr[][5], int rows, int cols) { int sum {0}; for(int y {0}; y < rows; ++y) { for(int x {0}; x < cols; ++x) sum += arr[y][x]; } return sum; } int main() { int arr[3][5] { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} }; std::cout << "Sum of array elements: " << sumArray(arr, 3, 5); } Hth, cmiiw
28th Jul 2018, 1:35 PM
Ipang
+ 2
Actually there are several ways to do that but I forgot the other ways, only slightly remember it passes the array as pointer. Yes the easiest way would be to use vectors, as there are no such restrictions on vectors, and they contain their own properties (e.g. size). Here also I get the same message, that dimensions need to be specified, except for the first. Sorry, I can't help you any further now, but I might come back if I find something and if you still haven't had a solution.
28th Jul 2018, 1:54 PM
Ipang
0
You can just pass them like any other variable. Maybe your array had more or less dimensions than the function needed or you didn't declare it correctly. Please post a link to your code here.
28th Jul 2018, 1:33 PM
Moritz Vogel
Moritz Vogel - avatar
0
Okay, but is there a way to pass one without knowing the size of the second dimension? I need a more generic solution. I could use vectors, but I don't want to rely on these.
28th Jul 2018, 1:45 PM
Lorenzo Romeo
Lorenzo Romeo - avatar