I need som help outputting the content of this multidimensional array. I'm trying pass the address of the array to the function and let it grab and run thru it.
#include <iostream>
using namespace std;
void LoopDeLoop(int[][] *arr)
{
for(int k = 0; k < 3; k )
{
for(int j = 0; j < 4; j )
{
cout << arr[k][j];
}
}
}
int main() {
int arr[3][4] = { {1,2,3,4}, {5,6,7,8}, {10,11,12,13} };
LoopDeLoop(&arr);
return 0;
}
CodePudding user response:
This pattern you are trying to use is old fashioned C.
Modern C way to do it should be more clear for you:
#include <array>
#include <iostream>
using MyArray = std::array<std::array<int, 4>, 3>;
void LoopDeLoop(const MyArray& arr)
{
for (auto& row : arr) {
for (auto x : row) {
std::cout << x << ' ';
}
std::cout << '\n';
}
}
int main()
{
MyArray arr { std::array { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 10, 11, 12, 13 } };
LoopDeLoop(arr);
return 0;
}
https://godbolt.org/z/Mbcjf9bx5
CodePudding user response:
C allows to pass plain array by reference and also automatically deduce dimensions using templates:
#include <iostream>
using namespace std;
template <int Rows, int Cols>
void LoopDeLoop(int const (& arr)[Rows][Cols])
{
for(int k = 0; k < Rows; k )
{
for(int j = 0; j < Cols; j )
{
cout << arr[k][j];
}
}
}
int main() {
int arr[3][4] = { {1,2,3,4}, {5,6,7,8}, {10,11,12,13} };
LoopDeLoop(arr);
return 0;
}
Output:
1234567810111213