【问题标题】:How to put 2-dimensional Array's pointer to the function as the parameter [duplicate]如何将二维数组指针作为参数[重复]
【发布时间】:2016-01-10 05:18:50
【问题描述】:

我正在使用 C++ 解决算法问题。

我想通过init输入动态放置每个维度大小不同的二维数组的指针。

我编码为函数的内容如下:内容(函数的函数)没有任何意义。

int cal(int **arr){
int test = arr[0][0];
return 0;
}

以及这个函数的结果

int arrayD[totalGroupCount][totalBeadCount];

int a = cal(arrayD);

它只是说“没有对'cal'的匹配函数调用”

我确实声明了函数“cal”。

我做了很多不同的符号

int cal(int *arr[]){
int test = arr[0][0];
return 0;
}

但它和我说的一样。

我已经搜索过这个问题,但得到的答案却是同样的错误(我完全不明白他们是怎么做到的)

【问题讨论】:

  • 请注意int arr[0][0] 的类型实际上是int * 而不是int **
  • 请阅读多维数组,例如这里:cplusplus.com/doc/tutorial/arrays
  • 另请注意,&arrayD 不是 int**
  • @qarma:呃,什么? int arr[x][y] 的类型是 int[x][y] 而不是 int*
  • 你想使用int cal((arrayD*) [totalBeadCount]);

标签: c++ arrays parameter-passing


【解决方案1】:

您需要使用malloccallocnew 分配内存:

long a;
int **pt; // a pointer to pointer to int
pt=new int*[rows]; // allocate memory for pointers,
// not for ints

for (a=0;a<rows;++a) pt[a]=new int[columns]; // here you're allocating
// memory for the actual data

这将创建一个类似于pt[rows][columns] 的数组。

然后你像这样传递pt

int Func(int **data) {
//do something
return //something
}

Func(pt);

【讨论】:

  • 这是唯一的答案吗?这很复杂,我不明白为什么我应该这样编码,而不是使用基本方式
  • @LKM,basic是什么方法?
  • @lkm 这不是您正在做的基本方式,而是一种称为可变长度数组的非标准 C++ 扩展。
  • 字数过多。只需“使用std::vector”即可。
  • 不,OP 非常清楚地没有提到向量。通常人们想解决问题,而不是使用特定的图书馆设施。
【解决方案2】:

当您使用 c++ 时,std::vector&lt; vector&lt;int &gt; &gt; 有更好的解决方案

int cal(std::vector<std::vector<int> > arr)
{
    int test = arr[0][0];
    return 0;
}

并调用函数

std::vector<std::vector<int> >arrayD (totalGroupCount, std::vector<int>(totalBeadCount));
int a = cal(arrayD);

您还可以使用push_back() 函数将元素动态添加到向量中。

【讨论】:

    猜你喜欢
    • 2019-03-17
    • 2016-03-23
    • 2017-02-03
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 2015-11-04
    • 2016-05-28
    相关资源
    最近更新 更多