传递到函数中的 C++ 2D 数组

c++ 2d array passing into a function

本文关键字:C++ 2D 数组 函数      更新时间:2023-10-16

我正在尝试为我的论文开发代码,为此我试图学习如何将 2D 数组传递给函数。我写了一些东西。代码在下面,它不能以这种形式工作。我遇到此错误:

错误:无法将参数"3"的"float (*)[((sizetype)((ssizetype)n) + -1)) + 1)]"转换为"float (*)[2]",将参数"3"转换为"void func(int, int, float (*)[2], float)"  Func(m, n, a, omega);

当我更改此矩阵声明浮点数 a[m][n]; 浮点数 a[2][2] 时,它正在工作。提前谢谢你。

    void func(int m1, int n1, float a1[2][2], float omeg);
using namespace std;
int main(){
    int m = 2;
    int n = 2;
    int i, j;
    float a[m][n];
    float x,y,z,omega, c;
    x=0.1;
    y=0.2;
    z=0.3;
    c = 0;
    omega = (x*y*z)/x;
    for(j = 0; j < n; j++)
    {
        for(i = 0; i < m; i++)
        {
        a[i][j] = 0.0;
        }
    }
    func(m, n, a, omega);
    cout << a[1][0] << endl;
return 0;
}
void func(int m1, int n1, float a1[][2], float omeg)
{
    for(int j = 0; j < n1; j++)
        {
            for(int i = 0; i < m1; i++)
            {   
            a1[i][j] = omeg * 5;
            }
        }
}

使用 const 表示mn,否则使用非标准扩展可变长度数组 (VLA)。

我建议使用更直观的std::array(如果大小是动态的,则std::vector)。

据我了解,宣言

float a[m][n]

是不可能的。不可能以这种方式指定可变或常量数组大小。声明为

float a[2][2]

如果大小实际上是 2 x 2,则更好阅读,但在内部它与声明相同

float (*a)[2]

被使用。对于 C 数组,在定义数组并将固定大小的数组声明为参数后不可能知道大小是不可能的,至少不可能达到预期的效果。

试试这个:-

int main(){
     int i, j;
     float a[2][2];
     float x,y,z,omega, c;
     x=0.1;
     y=0.2;
     z=0.3;
     c = 0;
     omega = (x*y*z)/x;
     for(j = 0; j < 2; j++)
     {
       for(i = 0; i < 2; i++)
         {
           a[i][j] = 0.0;
         }
     }
     func(a, omega);
     cout << a[1][0] << endl;
     return 0;
   }
   void func(float a1[2][2], float omeg)
   {
    for(int j = 0; j < 2; j++)
     {
        for(int i = 0; i < 2; i++)
        {   
        a1[i][j] = omeg * 5;
        }
    }
   }