2

I'm trying to count how many chars there in a 2D grid using 2 for loops. The code looks like this:

int number_of_boxes( int player, int height, int width, char**gameBoard ){
 int boxCount, i , a;
  for(i=0; i < (height*2) + 1 ; i++){
   for ( a = 0 ; a < (width * 2) + 1 ; a++){
      if(gameBoard[i][a] == (char)(player + 64)) boxCount++;
   }
  }
 return boxCount;
}

The player variable is an index for each player but in the grid they show ASCII characters.

1 = A, 2 = B and so on by adding 64 to the index and treating it like a char. The if state intends to check over every character in the array of arrays for the ASCII character and add to a counter if it finds an instance of one.

For some reason, the if statement in this function is passing way too many times and the function is returning 122 or 120 when the only possible maximum is 4. Is my if statement wrong?

TryinHard
  • 4,078
  • 3
  • 28
  • 54

2 Answers2

2

You haven't initialized boxCount.

 int boxCount, i , a;

Therefore boxCount currently stores some garbage value. I think thats why you assume that the if statement runs for many times.Try initializing boxCount.

  int boxCount=0, i , a;
Sourav Kanta
  • 2,727
  • 1
  • 18
  • 29
0

You missed out on initializing the boxCount:

Replace

int boxCount, i , a;

with

int boxCount=0, i , a;

Since the incrementing the uninitialized values is undefined.

TryinHard
  • 4,078
  • 3
  • 28
  • 54