将数组作为指针参数传递

时间:2015-04-20 05:21:39

标签: c++ arrays pointers

当我遇到这个问题时,我试图更多地使用数组和指针:

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);

如果我错过了一些重要的概念或者没有看到一个非常简单的错误,请告诉我。

4 个答案:

答案 0 :(得分:1)

如果您愿意使用我强烈推荐的std::vector,您可以使用以下代码创建2D矢量:

using std::vector<int> Vec1;
using std::vector<Vec1> Vec2;
using std::vector<Vec2> Vec3;

Vec3 a(2, Vec2(5, Vec1(10, 0));

然后将arrayLearn的参数更改为const Vec3&,使用a调用它。

void arrayLearn(const Vec3& arg) 
{
   // You'll need to use three loops to traverse all the elements.
   for ( auto const& v2 : arg )
   {
       for ( auto const& v1 : v2 )
       {
           for ( auto const& item : v1 )
           {
              // Use item
           }
       }
   }
}

答案 1 :(得分:1)

Abhishek所述,您正在尝试将三维数组传递给一维对象。

如果在其他地方没有使用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];

答案 2 :(得分:0)

简单来说,ary是3维的,show是1维的。编译错误告诉您无法将3D转换为1D。现在,为什么以下工作?

arrayLearn(ary[5][10]);

这是因为,ary[5][10]指的是1D(行或列或高度,取决于您如何可视化3D数组),arrayLearn也接受1D参数。

如果您想使用ary传递show,请将ary[5][10]之类的2D传递给show变量,如下所示:)

show = ary[5][10];

答案 3 :(得分:0)

你可以使用STL数据结构,如vector,map,linkedlist,... 在实现和性能方面,所有这些都更好。

但是为了解决这个问题,你必须以这种方式将3维数组传递给一个函数:

int array[10][7][8];

 void function_sample(int (*a)[7][8] , int length)
 {
     //for example for printing array cells
    for(int i =0 ; i< length ; i++)
    {
        for(int j =0 ; j< 7 ; j++)
        {
            for(int k =0 ; k< 8 ; k++)
            {
                cout << a[i][j][k] << endl
            }
        }
    }

    //....
 } 

并且用于调用此函数:

int array[10][7][8] //= {initial your array};
function_sample(array , 10);