Here is the function:
void printArray(const char arr[][3], int rows, int cols) {
// rows == 3 && cols == 3 is currently a placeholder. I have to confirm whether these are
// actually correct.
if (rows == 3 && cols == 3 && rows > 0 && cols > 0 && rows <= SIZE && cols <= SIZE) {
for (int i = 0; i < rows; i ) {
for (int j = 0; j < cols; j ) {
cout << arr[i][j];
}
cout << '\n';
}
}
}
I need to figure out if the rows parameter inputted into the equation is actually correct. To do this, I need to calculate the size of the const char array from within the function.
I have tried adding the following to the if statement:
rows == sizeof(arr)/sizeof(arr[0]) cols == sizeof(arr[0])/sizeof(arr[0][0])
rows == sizeof(arr)/sizeof(arr[0]) cols == sizeof(arr[0])
None of these have worked. Please advise many thanks.
CodePudding user response:
It does not work this way. arr
is a pointer type (const char (*)[3]
) and you cannot derive a size from it unless you use a function template:
#include <iostream>
using std::cout;
template <int rows, int cols>
void printArray(const char (&arr)[rows][cols])
{
static_assert(rows == 3 && cols == 3, "Dimension must be 3x3, mate!");
for (int i = 0; i < rows; i ) {
for (int j = 0; j < cols; j ) {
cout << arr[i][j];
}
cout << '\n';
}
}
int main()
{
char good[3][3] {};
char bad[2][3] {};
printArray(good);
printArray(bad);
}
Note that the above will automatically infer the dimensions from the array, and create an appropriate function. Additionally, there's a static assertion here that will fail to compile for anything other than a 3x3 array:
error: static assertion failed: Dimension must be 3x3, mate!
8 | static_assert(rows == 3 && cols == 3, "Dimension must be 3x3, mate!");
| ~~~~~^~~~
CodePudding user response:
My advise top using "C" style arrays and move to C std::array.
//You could change your call to arr[3][3] but in general I would advice to switch to using std::array or std::vector in C .E.g.printArray
#include <array>
#include <iostream>
// array is an object so unlike "C" style arrays you can return them from functions
// without having to use something like char** (which looses all size information)
std::array<std::array<char,3>,3> make_array()
{
std::array<std::array<char, 3>, 3> values
{ {
{'a','b','c'},
{'d','e','f'},
{'g','h','i'},
} };
return values;
}
// pass by const reference, content of array will not be copied and not be modifiable by function
// only will compile for 3x3 array
void show(const std::array<std::array<char, 3>, 3>& values)
{
// use range based for loops they cannot go out of bounds
for (const auto& row : values)
{
for (const char value : row)
{
std::cout << value;
}
std::cout << "\n";
}
}
int main()
{
auto values = make_array();
show(values);
return 0;
}
Note : the size of the arrays can be templated so your code will work for other array/matrix sizes as well.