1

The program is just for passing complete 2-d array to function.I am able to run the problem by hook or by crook but i didnt understood.I have written a program which i should have written threotically and which i have written to make it working(in comments) can anyone please explain me this issue??

#include<iostream>
#include<conio.h>
void print(bool *a);
using namespace std;
int main()
{
    bool arr[3][3]={1,1,1,1,0,0,0,1,1};
    print(arr[0]);//**This IS working but why  we need subscript 0 here only print(arr) should work?..**
    getch();
    return 0;
}
void print(bool *a)
{

    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
            {
                cout<<*(a+i*3+j)<<"|";//**cant we use cout<<a[i][j] here??In 1 d array it is working fine**
            }
            cout<<"--";
    }

}
4

2 回答 2

3
void print(bool *a)

应该

void print(bool a[][3])

编译器需要知道第二维的大小才能计算寻址偏移量。

void print(bool a[][3], int rowSize)
{
   for(int i=0;i<rowSize;i++)
   {
     for(int j=0;j<3;j++)
     {
        cout<<a[i][j]<<"|";
     }
     cout<<"--";
}

在 C++ 中,您应该更喜欢使用vector<vector <bool> >2D 动态数组arr

于 2013-04-14T20:29:15.933 回答
1

利用:

 void print(bool a[][3])

如果您想调用,这是正确的原型print(arr);

然后您可以使用a[i][j]访问print函数体中的数组元素。

arr是数组的数组3bool当传递给print函数调用时,arr表达式将转换为指向数组3的指针bool

于 2013-04-14T20:28:27.037 回答