简体   繁体   中英

c++ 2d array passing into a function

I am trying to develop a code for my thesis and for that I was trying to learn how to pass a 2D array to a function. I wrote something. The code is in the below and it is not working in this form. I am having this error:

error: cannot convert ‘float (*)[(((sizetype)(((ssizetype)n) + -1)) + 1)]’ to ‘float (*)[2]’ for argument ‘3’ to ‘void func(int, int, float (*)[2], float)’
  func(m, n, a, omega);

When I change this matrix declaration float a[m][n]; to float a[2][2] it is working. Thank you in advance.

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

}

Use const for m and n , else you use a non-standard extension variable length array(VLA).

I suggest to use std::array which is more intuitive (or std::vector if size is dynamic).

To my understanding, the declaration

float a[m][n]

is not possible. It is impossible to specify variable or constant array sizes this way. The declaration as

float a[2][2]

is nicer to read if the size is actually 2 by 2, but internally it is the same as if the declaration

float (*a)[2]

is used. For C arrays, it it impossible to know the size after definition of the array and declaration of an array of fixed size as a parameter is impossible, at least not with the desired effect.

Try this :-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM