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.
2
Answers
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: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 3×3 array:
My advise top using "C" style arrays and move to C++ std::array.
Note : the size of the arrays can be templated so your code will work for other array/matrix sizes as well.