<分区>
为什么后面的 boolean 值“mat”的二维地址不能像这样传递给函数?
void generate(bool arr) {
......;
......;
}
int main() {
bool mat[3][3];
generate(mat);
return 0;
}
<分区>
为什么后面的 boolean 值“mat”的二维地址不能像这样传递给函数?
void generate(bool arr) {
......;
......;
}
int main() {
bool mat[3][3];
generate(mat);
return 0;
}
最佳答案
尝试以下示例 然后注意以下描述:
const int N = 3;
void generate(bool arr[][N]) {
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
std::cout << std::boolalpha << arr[i][j] << " ";
}
std::cout << std::endl;
}
}
int main() {
// initialize array
bool mat[N][N] = { {1, 0, 1},
{0, 1, 0},
{1, 0, 1} };
generate(mat);
return 0;
}
输出:
true false true
false true false
true false true
注意: 有 3 种方法可以将二维数组传递给函数,完全符合 (this answer):
函数参数是一个二维
数组:
bool arr[10][10];
void Func(bool a[][10])
{
// ...
}
Func(arr);
函数参数是一个指针数组:
bool *arr[10];
for(int i = 0;i < 10;i++)
arr[i] = new bool[10];
void Func(bool *a[10])
{
// ...
}
Func(arr);
函数参数作为指针
指向指针
:
bool **arr;
arr = new bool *[10];
for(int i = 0;i < 10;i++)
arr[i] = new bool[10];
void Func(bool **a)
{
// ...
}
Func(arr);
关于c++ - 将二维 boolean 值传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52177589/