[英]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
. arr
是bool
数组3
的数组,当传递给print
函数时, arr
表达式被转换为指向bool
数组3
的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.