check if a matrix is symmetric and i get always the same result

  • A+
Category:Languages

I wrote a function that checks if the matrix is Symmetric . If it is, it will return 1, otherwise 0 . It always returns zero. I tried to figure out where the mistake is, but everything seems correct to me.

My code is:

#include <stdio.h> #include <stdlib.h> #define max 100  int Symmetrie (int matrix[][max]) {   int i,j;   for(i=0;i<4;i++) {     for(j=0;j<4;j++) {       if(matrix[i][j] != matrix[j][i]) {         return 0;       }     }   }   return 1; }  int main() {   int x;   int  square_matrix[][max]={{1,2,3,4}     ,{2,2,5,6}     ,{3,5,3,7}     ,{4,6,7,4}   };   x= Symmetrie(square_matrix[4][4]);   if(x==1) {     printf("1");   } else {     printf("0");   }   return 0; } 

The function should return 1, but it returns zero. What am I missing?

 


Change this:

x= Symmetrie(square_matrix[4][4]); 

to this:

x = Symmetrie(square_matrix); 

since your method expects the whole matrix as its parameter, not just an element.

square_matrix[4][4] is a single element of the matrix, i.e. the element in 5th row and 5th column. Of course this invokes Undefined Behavior (UB), since your matrix has 4 rows.

More importantly, don't ignore the warnings generated. In GCC for example you would get something like this:

prog.c: In function 'main': prog.c:24:32: warning: passing argument 1 of 'Symmetrie' makes pointer from integer without a cast [-Wint-conversion]    24 |   x= Symmetrie(square_matrix[4][4]);       |                ~~~~~~~~~~~~~~~~^~~       |                                |       |                                int prog.c:5:20: note: expected 'int (*)[100]' but argument is of type 'int'     5 | int Symmetrie (int matrix[][max]) {       |                ~~~~^~~~~~~~~~~~~ 

as you can see in the Live Demo.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: