problem with passing array to function

I have to program
a function that finds the max element in a 2-dimensional array. So I wrote this code:


#include <iostream>
using namespace std;
float func(int m, int n, float a[])
{
    int i,j;
    float max=0;
    for (i=0;i<m;i++)
    {
        for (j=0;j<n;j++)
        {
            if (max<a[i][j]) max=a[i][j];
        }
    }
    return max;
}
int main()
{
    int i,j,m,n;
    cin>>m>>n;
    float a[m][n];
    for (i=0;i<m;i++)
    {
        for (j=0;j<n;j++)
        {
            cin>>a[i][j];
        }
    }
    cout<<func(m,n,a);
}


But I keep getting errors like

|28|error: cannot convert 'float (*)[(((unsigned int)(((int)n) + -0x000000001)) + 1)]' to 'float*' for argument '3' to 'float func(int, int, float*)'|

and

error: invalid types 'float[int]' for array subscript|

Can someone tell me what am I doing wrong?
I would say that your problem is in this line:
float a[m][n];

You can't create an array with regular variables for the size.

My suggestion is to use float a[1000][1000];. The only limitation here is that m and n need to be below 1000.

Or maybe:
1
2
3
cin >> m >> n;
const int o = m, p = n;
float a[o][p];
I would say that your problem is in this line:
float a[m][n];


You can't create an array with regular variables for the size.

My suggestion is to use
float a[1000][1000];
. The only limitation here is that m and n need to be below 1000.

Or maybe:

cin >> m >> n;
const int o = m, p = n;
float a[o][p];


Nope, tried both ways, still doesn't work and gives out the same errors.
Last edited on
To make arrays with non-constants, you'll need to use the new keyword.
http://www.cplusplus.com/reference/std/new/operator%20new%5B%5D/

But, remember, that when you've created something with new you'll need to delete it after!
http://www.cplusplus.com/reference/std/new/operator%20delete%5B%5D/

Have a look at this to create/delete a 2d array:
http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-using-new

Also, in your code, you're passing a 2d array[][] to a function expecting a 1d array[].
Topic archived. No new replies allowed.