2 dimensional arrays passed to a function in c++
I'm working on doing calculations in a two dimensional array
but keep getting a nasty error.
i call the function by :
if(checkArray(array))
and try to pass it in like this:
bool checkArray(double array[][10]) //or double *array[][10] to no avail
the error is
error: cannot convert ‘double ()[(((unsigned int)(((int)n) + -0x00000000000000001)) + 1)]’ to ‘double’ for argument ‘1’ to ‘bool checkArray(double*)’
code snippet
//array declaration
in开发者_开发百科t n = 10;
double array[n][n];
//function call to pass in array
while(f != 25)
{
cout<<endl;
cout<<endl;
if(checkArray(array)) //this is the line of the error
{
cout<<"EXIT EXIT EXIT"<<endl;
}
f++;
}
//function declaration
bool checkArray(double *array)//, double newArray[][10])
{
double length = sizeof(array);
for(int i = 0; i < length; i++)
for(int j = 0; j < length;j++)
{
double temp = array[i][j];
}
}
When I look at the error you are getting, I have an impression that your function has got invalid declaration. It looks like as if it would expect only one-dimensional array: double*.
However, your question seems a little unclear for me... Could you paste the function code?
Is this really a direct (if edited) copy of your code?
This line:
int n = 10; double array[n][n];
is not valid C++. You can't declare an array with variable dimensions. This would work:
const int n = 10; double array[n][n];
You want to declare checkArray as:
bool checkArray(double array[][10])
and you absolutely do not want to do this:
double length = sizeof(array);
because that will assign to length
the size of a pointer, in bytes (4 or 8.) You need to pass in the number of rows explicitly. Also, you're much better off declaring length
as an int
, or better yet a size_t
.
This seems like a decent resource: http://www.fredosaurus.com/notes-cpp/arrayptr/22twodim.html
精彩评论