c++ - 无法在 C++ 中遍历二维数组

标签 c++ arrays boolean

<分区>

我正在为我的测试学习 C++,我以前学习 java,现在有很多困惑。 我正在尝试打印 boolean 值的二维数组,如果为真,则返回#,如果为真,则返回?如果是假的。我已经尝试先初始化数组,我认为这是可行的,如果我不使用迭代器 (printGrid),我可以在特定数组位置打印值。下面是我的代码

 #include<iostream>

 void printGrid(bool a[][10]){ // why this method doesn't work?

    for(int i = 0; i < sizeof(a)/ (sizeof(*a)) ; i++){
        for(int j = 0; j < sizeof(a)/ (sizeof(*a)) ; j++) {
            char x = a[i][j] ? '#' : '?'; // i've using the conditional in my std::cout before, still doesn't work
            std::cout << x;

        }
        std::cout<< std::endl;
    }

   }
void main(){
    bool grid[10][10];
        for(int i = 0; i < sizeof(grid)/sizeof(*grid) ; i++){
        for(int j = 0; j < sizeof(grid)/sizeof(*grid); j++){

            grid[i][j] = 1;
        }

    }
    printGrid(grid); // this doesn't work
    std::cout<<( (grid[0][1]) ? "#" : "?" ) << std::endl; // this works fine
    getchar();

} // main

我的 printGrid 哪里错了? 我已经尝试使用 INT 的二维数组来代替相同的设置,函数在 main 之外等,并且它工作得很好。有什么想法吗?

编辑:非常感谢您的回答。我的问题还没有得到回答,我的功能有什么问题?因为我试过使用具有相同设置、只是参数不同的方法,而且效果很好

void printint(int a[][10]){ // why does this work, and the above doesn't?
for(int i = 0; i < 10 ; i++){
        for(int j = 0; j < 10 ; j++) {

            std::cout <<( (a[i][j] == 10) ? "a" : "b");

        }
        std::cout << std::endl;
    }
}

当我使用 printint 打印我的 2D 数组时,它工作得很好吗?

最佳答案

bool a[][10]实际上是bool (*a)[10] , 所以 sizeof (a)是指针的大小。

通过引用传递数组:

void printGrid(const bool (&a)[10][10])

Live example

使用 std::array<std::array<bool, 10u>, 10u>具有更直观的界面。

关于c++ - 无法在 C++ 中遍历二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26612277/

相关文章:

python - 将包含字符串的 Pandas 系列转换为 boolean 值

java - 计算 n 个 boolean 值的 "trues"的数量

c++ - 删除指向抽象类的指针 vector

javascript - 如何将额外的参数传递给 JS Array.forEach()

Java 用一维数组填充二维数组

html - 如何垂直填充表格数据?

java - 使用 boolean 对象

c++ - 在 Windows 7 32 位上使用 Visual Express C++ 2012 设置 Qt 5

c++ - "numrt": identifyer not found despite of defining that function

C++ 对一个定义规则的混淆