无法在C++中遍历2D数组

fail to iterate through 2D array in C++

本文关键字:遍历 2D 数组 C++      更新时间:2023-10-16

我正在为我的测试学习C++,我以前在那里学习java,现在有很多困惑。我正在尝试打印布尔值的2D数组,如果为true,则返回#,并且?如果为false。我已经尝试过首先初始化数组,我认为这是有效的,如果我不使用迭代器(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的2D数组,使用相同的设置,使用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])

实例

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

这里,您将数组传递给一个函数,该函数被转换为指针,因此您将得到的只是指针的大小。

记住,当传递格式请求数组衰减时,数组衰减为指针,即如果相应的参数被声明为指针(在这种情况下)。如果参数被声明为对数组的引用,则衰减不会发生