Well -- you should listen to your compiler -- it is correct.
When you have a 2D array (which is actually and array of array double [3]
), on access, the first level of indirection (the first [..]
) is converted to a pointer to the first element. So double arr[2][3];
is converted to a pointer-to-array double[3]
. (a pointer to the first array of the 2 double[3]
arrays). The type for a pointer-to-array double[3]
is double (*)[3]
-- just as your compiler is telling you.
To make things work correctly, your prototype should be:
int numberNegative (double (*arr)[3], int r, int c);
Then within your function, you can count the number of negative values with:
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (arr[i][j] < 0)
counter++;
}
}
return counter;
Note: j < c
NOT j <= c
(which exceeds the bounds of the array by 1) and no if (arr[i] < 0) counter++;
which attempts to compare an pointer to double
to 0
.
Further, you cannot have return counter;
within your for
loop and expect to return the correct value for all negative values in your 2D array. Where you do:
for (int i = 0; i < r; i++){
...
return counter;
}
You need to move return counter;
out of the loops to the end (last statement) in your function.
There is no need for a global int counter;
and see Why is “using namespace std;” considered bad practice?
Putting it altogether, you would have:
#include <iostream>
int numberNegative (double (*arr)[3], int r, int c);
int main (void) {
double data[2][3] = {{-3.0, 1, 4.5}, {-2.2, 7, 1.4}};
std::cout << numberNegative (data, 2, 3) << '\n';
}
int numberNegative (double (*arr)[3], int r, int c)
{
int counter = 0;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (arr[i][j] < 0)
counter++;
}
}
return counter;
}
See also: C++: “std::endl” vs “\n”
Example Use/Output
$ ./bin/count_double_neg
2
Which corresponds to -3.0
and -2.2
. Look things over and let me know if you have any questions.