简体   繁体   English

将2-d数组传递给函数时出错

[英]error in passing 2-d array to function

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<<"--";
    }

}
void print(bool *a)

should be 应该

void print(bool a[][3])

the compiler needs to know the size of second dimension in order to compute offset for addressing. 编译器需要知道第二维的大小,以便计算寻址的偏移量。

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<<"--";
}

In C++, you should prefer using vector<vector <bool> > over 2D dynamic array arr . 在C ++中,您应该优先使用vector<vector <bool> >不是2D动态数组arr

Use: 采用:

 void print(bool a[][3])

which is the correct prototype if you want to call print(arr); 如果你想调用print(arr);这是正确的原型print(arr);

Then you can use a[i][j] to access array elements in the print function body. 然后,您可以使用a[i][j]访问print功能体中的数组元素。

arr is an array of array 3 of bool and when passed to print function call the arr expression is converted to a pointer to an array 3 of bool . arrbool数组3的数组,当传递给print函数时, arr表达式被转换为指向bool数组3的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM