当我遇到这个问题时,我试图深入研究使用数组和指针:
main.cpp:13:7: error: cannot convert 'int [2][5][10]' to 'int*'
分配中 show=ary;
这是代码:
#include <iostream>
using namespace std;
void arrayLearn(int *);
int main()
{
int ary[2][5][10];
int *show;
ary[2][4][9]=263;
ary[2][5][10]=100;
show=ary; //line 13
arrayLearn(show); //line 14
cout <<"End process"<<endl;
return 0;
}
void arrayLearn(int *arg)
{
for(int i=0;i<100;i++)
{
cout<<"Pointer position: "<<i<<" Value: "<<*(arg++)<<endl;
}
}
如果我删除第13行并将第14行替换为以下代码,
arrayLearn(ary[5][10]);
然后程序进行编译,但是我不明白为什么我应该只传递两个维度而不是三个维度。如果我将指针传递给数组中的第一项,那为什么不能只像这样传递指针呢?
arrayLearn(ary);
如果我错过了一些重要概念或未能看到一个非常简单的错误,请告诉我。
如Abhishek所述,您正在尝试将3维数组传递给1维对象。
如果show
未在其他任何地方使用该变量,则可以执行以下操作:
#include <iostream>
using namespace std;
void arrayLearn(int *);
int main()
{
int ary[2][5][10];
// Code change explained below (see Note)
ary[1][4][8] = 263;
ary[1][4][9] = 100;
// Pass the starting address of the array
arrayLearn(&ary[0][0][0]);
cout <<"End process"<<endl;
return 0;
}
// Iterate through the array using the position of the elements in memory
void arrayLearn(int *arg)
{
for(int i=0;i<=100;i++)
{
cout<<"Pointer position: "<<i<<" Value: "<<*(arg++)<<endl;
}
}
输出:
...
Pointer position: 98 value: 263
Pointer position: 99 value: 100
End process
通过这种方式,您可以将数组的起始地址传递给函数。
注:应该指出的是,原来的数组赋值ary[2][4][9] = 263;
和ary[2][5][10] = 100;
在外面的数组的边界。数组索引从0开始。因此,即使您将数组声明为ary[2][5][10];
要访问最后一个数组元素,也应使用ary[1][4][9];
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句