2d array

I am trying to initialize a 2 dimensional bool array to false with a constructor. I have a print function that is to display an '*' for each element of the array if each element is false, but instead it is printing the else statement as true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// In main
boolMatrix matrix1;
	matrix1.print();
}




  boolMatrix::boolMatrix()
{
	for (int row = 0; row < NUM_ROWS; row++) {
		for (int col = 0; col < NUM_COLS; col++) {

			bool array[NUM_ROWS][NUM_COLS] = {false};
		}
	}
}



void boolMatrix::print()
{
	for (int row = 0; row < NUM_ROWS; row++) {
		for (int col = 0; col < NUM_COLS; col++) {

			if (array[NUM_ROWS][NUM_COLS] == false) {
				cout << "*";
			}
			else cout << "true";
			
		}
	}
}
Line 14: You're initializing a local array, not your member array. array goes out of scope at line 15. get rid of the word bool. You member array is never initialized and therefore contains garbage.

BTW, I have to guess here that array is a member variable of your class since you did not show you class declaration.,
Last edited on
Okay I see it. Shouldn't have the bool data type in the for statement.
> 14 bool array[NUM_ROWS][NUM_COLS] = {false};
You're creating an entirely new local array with a very limited scope.

Use your loop variables as subscripts (in both functions).

bool array[row][col] = false;

if ( array[row][col] == false )
Show the definition of the class. We cannot see how you declare the boolMatrix::array.

You have same issue as in this program:
1
2
3
4
5
6
7
8
9
#include <iostream>

int main() {
    int answer = 7;
    if (answer) {
        int answer = 42;
    }
    std::cout << answer;
}

 In function 'int main()':
6:13: warning: unused variable 'answer' [-Wunused-variable] 

The answer is created and initialized but never used.
The other answer is used.
Do you understand why the answer of local scope masks/hides the answer of outer scope?
Topic archived. No new replies allowed.