這是功能:
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';
}
}
}
我需要弄清楚輸入到方程中的行引數是否真的正確。為此,我需要從函式內計算 const char 陣列的大小。
我嘗試在 if 陳述句中添加以下內容:
rows == sizeof(arr)/sizeof(arr[0]) cols == sizeof(arr[0])/sizeof(arr[0][0])
行 == sizeof(arr)/sizeof(arr[0]) cols == sizeof(arr[0])
這些都沒有奏效。請多多指教,謝謝。
uj5u.com熱心網友回復:
它不能以這種方式作業。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!");
| ~~~~~^~~~
uj5u.com熱心網友回復:
我的建議是使用“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;
}
注意:陣列的大小可以模板化,因此您的代碼也適用于其他陣列/矩陣大小。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/524226.html
標籤:C 数组代码功能字符
上一篇:當資料庫中的外鍵關系為空時使用OdataAPI,拋出SqlNullValueException:DataisNull例外
下一篇:如何分配通過條件陳述句的變數
