Checking if matrix is Toeplitz, when it is not, the code crashes on ***. Don't know why the if statement can't stop it.
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
if (j == 0 || i == 0) {
for (k = 0;; k++) {
if ((i + k) < M && (j + k) < N) {
// *** the code crashed here
if (matrix[i + k][j + k] != matrix[i][j]) {
z = 1;
} else if ((i + k) == (M - 1) || (j + k) == (N - 1)) {
break;
}
}
}
}
}
}
The inner
forloop can keep going without ever reaching thebreakstatement. In this case,kkeeps increasing until it reachesINT_MAXand then you have undefined behavior when incrementing it or even before when computingi + kand/orj + k. What is probably happening isi + korj + kbecomes a large negative value and passes the testi + k < Nbut causes a segmentation fault when you try and read frommatrix[i + k][j + k].Here is a modified version:
Note however that these nested loop will iterate many more times than necessary to determine the matrix property. You could rewrite the loops as:
a Toeplitz matrix or diagonal-constant matrix, named after Otto Toeplitz, is a matrix in which each descending diagonal from left to right is constant. A more direct way to test this property is this:
Or as a function: