Reputation:
I am working on a magic square problem that uses a dynamic matrix of size n*n. It fills the matrix with numbers 1-n^2, and the sum of each row, column, and diagonal must be the same. One of the conditions of the algorithm is to check if an element in the matrix already had a number input in it during one of the loops. I am having problems checking if one of the elements in the matrix already had a number inputed in it, so I am wondering how to check if an element is empty.
Here is my code for that portion of the algorithm:
else if(matrix[row][col] != 0)
{
row = row + 2;
col--;
}
For some reason it triggers this if statement on the 5th iteration of the encompasing loop. I have worked it out on paper using the algorithm for a magic square, and the 5th iteration of the loop brings it to an empty element in the matrix. I thought that if an element is empty it holds the value 0? I appreciate any help as I am very confused. Thank you.
Upvotes: 0
Views: 2226
Reputation: 206526
Array's in C and C++ are not empty by default. You need to explicitly set the elements to 0
or create the array in such a way that they are initialized to 0
.
What you are facing is Undefined Behavior. The uninitialized array has some random(read garbage) values and accessing those results in a Undefined behavior.
Array's created at global scope or with a static
qualifier will be initialized to 0
or you can use initialization provided built in by the language or you can explicitly set each element to 0
.
There are multiple ways of doing so, the best one depends on what behavior you want to extract from the array.
Upvotes: 4