如何计算接受这样一个输入的函数中2D字符数组的行数



以下是函数:

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';
}
}
}

我需要弄清楚输入到等式中的rows参数是否真的正确。为此,我需要从函数中计算const char数组的大小。

我尝试在if语句中添加以下内容:

rows==sizeof(arr(/sizeof(arr[0](cols==(arr[0](的大小/(arr[0][0](的大小

rows==sizeof(arr(/sizeof(arr[0](cols==的大小

这些都没有奏效。请多多建议,谢谢。

它不能以这种方式工作。arr是指针类型(const char (*)[3](,除非使用函数模板,否则无法从中派生大小

#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);
}

请注意,以上内容将自动从数组中推断维度,并创建适当的函数。此外,这里还有一个静态断言,它将无法编译3x3数组以外的任何东西:

error: static assertion failed: Dimension must be 3x3, mate!
8 |     static_assert(rows == 3 && cols == 3, "Dimension must be 3x3, mate!");
|                   ~~~~~^~~~

我的建议顶部使用"C";样式数组,然后移到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;
}

注意:数组的大小可以模板化,这样您的代码也可以用于其他数组/矩阵大小。

相关内容

  • 没有找到相关文章

最新更新