I made a comment, but I will also go ahead and respond with the fixed function. There were three main issues in the code that I'll point out:
- In your code, you have numbers within the array, but then you try comparing a char to a number (
'2' == 2
is false), so that means your result will be 0 over all
- The print statement was after the
return
, which means it won't actually run.
- the if statement
if (2 == d[ROWS][COLS])
is always going to check the number at position ROWS
and COLS
. The first issue there is that ROWS
and COLS
aren't changing positions, that's a constant; you want to check at the position i
and j
. Second, since array's in C are zero-based, accessing d
at position [ROWS][COLS]
will actually point to some unknown memory space since that's beyond the scope of the array, but that's just an interesting fact.
The following code should fix the problems I pointed out above:
char d[ROWS][COLS] = {
{0, 2, 0, 2, 0, 2, 0, 2},
{2, 0, 2, 0, 2, 0, 2, 0},
{0, 2, 0, 2, 0, 2, 0, 2},
{1, 0, 1, 0, 1, 0, 1, 0},
{0, 1, 0, 1, 0, 1, 0, 1},
{3, 0, 3, 0, 3, 0, 3, 0},
{0, 3, 0, 3, 0, 3, 0, 3},
{3, 0, 3, 0, 3, 0, 3, 0}};
int countOccurrences(char d[ROWS][COLS], int i, int j, int res) {
res = 0;
// NOTICE that it is now i < ROWS and j < COLS instead of
// i <= ROWS and j <= COLS to deal with what I mentioned
// before about the zero-based indexing in C, which means
// we need to stop BEFORE ROWS and COLS
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (2 == d[i][j])
res++;
}
}
printf("score%d", res);
return res;
}