【问题标题】:Passing standard and dynamic arrays to functions in c++将标准和动态数组传递给 C++ 中的函数
【发布时间】:2014-08-08 18:05:24
【问题描述】:

我正在学习 cpp,这与我正在处理的任务无关。我对编写接受动态多维数组的函数感到困惑。例如,如果我有两个一维数组,一个是动态的,另一个不是,我可以将它们中的任何一个传递给以下函数并让它们都工作:

// Regular 1D array
int b[] = {1,2,3};

// Dynamic 1D array
int *p_b;
p_b = new int[3];
for(int i=0;i<3;i++)
{
    p_b[i] = i;
}

//Function prototype. Works when I use printGrid(b) and printGrid(p_b)
void printGrid(int *a);

但是,如果我在使用 2D 数组时出现以下情况,那么只有在我传入动态数组时才会编译:

// Regular 2D array
int c[3][3] ={{1,2,3},{4,5,6,},{7,8,9}};

// Dynaimc 2D array
int **p_c;
p_c = new int*[3];
for(int i=0; i<3;i++)
{
    p_c[i] = new int[3];
}
for(int i=0; i<3; i++)
{
    for(int j=0;j<3;j++)
    {
        p_c[i][j] = i+j;
    }
}

// Function prototype - Compiles and works using printGrid2(p_c) but fails to compile     using printGrid2(c)
void printGrid2(int **a);

printGrid函数下面的代码完全一样,所以有两个函数似乎很浪费,一个使用a[][]作为参数,另一个使用int **a。我是不是不明白或错过了什么?提前致谢!

【问题讨论】:

  • int[][]int** 是两种不同的类型。
  • 确实,我们这里有两种不同的类型,它们在内存中的布局不同。 See this similar question 有很多好的回复。
  • @glampert - 感谢您的链接!

标签: c++ arrays dynamic


【解决方案1】:

这并不少见,您可以将 printGrid2 转发到 printGrid 以利用该功能(避免重复代码和维护开销)。

printGrid2 在第一个维度上循环并使用类似 a[0]..a[n] 的方式调用 printGrid

【讨论】:

  • 谢谢!这很有帮助。
猜你喜欢
  • 2010-09-25
  • 1970-01-01
  • 2020-05-05
  • 2011-08-16
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 2011-05-24
相关资源
最近更新 更多