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/

相关文章:

c - C 编程语言中的字符串到 boolean 值

C++ 错误 2679 : binary'>>' : no operator found

c++ - 是否可以从一个特定模板实例化的构造函数中删除关键字 "explicit"?

javascript - 使用由两个 .map() 组成的两个数组创建一个变量,寻找匹配项或交集

java - 使用排序方法逻辑时并非所有数组元素都显示

ruby - 方法中不熟悉的语法

c++ - 内存分配是什么意思

c++ - 基类构造函数真的在派生类构造函数之前被调用

javascript - 如何使用 underscore.js 或 jQuery 检查对象是否有空数组

sql - Oracle 数据库中有 boolean 类型吗?