Reputation: 3854
I have a 2D array that defined as
int P[5][10];
for (int i=0;i<N;i++)
{
for(int j=0;j<L;j++)
{
if(random()>0.5)
P[i][j]=1;
else
P[i][j]=0;
}
}
I want to make a function with input is P. The function allows us show the value of P. How to defined that function. I tried such as
void show_P(int P[][], int numcols,int numrows)
However, it is wrong. Could you help me fix it? Thanks
Upvotes: 1
Views: 381
Reputation: 227418
If you want to restrict the arguments to 5 by 10 2D arrays, you can pass by reference like this:
void show_P(int (&P)[5][10])
This will fail for any other type of array. If you want the function to work for other sizes, you can make it a template.
template <size_t N, size_t M>
void show_P(int (&P)[N][M])
Upvotes: 3
Reputation: 126
void print( int (&ref)[5][10]) {
for( auto &lm: ref) // get the first array from the multidimensional array and initialize lm with it
for( auto &elem: lm) // get the first element from lm
std::cout << elem << " "; // print the element
}
This only works with an array with dimensions as P i.e, [5][10]
Upvotes: 0
Reputation: 44284
Or using the std::array
void printArray(array<array<int,2>,3>& arr)
{
for (auto x : arr)
{
for (auto y : x)
{
cout << y << endl;
}
}
}
int main()
{
array<array<int,2>,3> arr{{{1, 2}, {2, 3}, {3, 4}}};
arr[0][1] = 5;
printArray(arr);
}
would give you:
1
5
2
3
3
4
Upvotes: 1
Reputation: 590
You could just change it to:
void show_P(int** P, int numcols, int numrows)
Passing 2D array always using the pointer.
Hope this will help.
Upvotes: 1