Home > front end >  Recursive Function to check if two matrices are equal using pointers
Recursive Function to check if two matrices are equal using pointers

Time:03-22

i have written this program to check if two matrices are equal or not. whenever i run it it gives me segmentation faults. As i am learning recursion so don't know about it much so if you all can help me.

int equal(int**matrix1,int**matrix2,int row,int col){
    if(col<0){
        col=row;
        row--;
    }
    if(row < 0){
        return 1;
    }
    if(matrix1[row][col]==matrix2[row][col]){
        return equal(matrix1,matrix2,row,col-1);
    }
    else{
        return 0;
    }
  }

int main(){

int **ptr1 = new int*[3];
int **ptr2 = new int*[3];
for(int i=0;i<3;i  ){
    ptr1[i] = new int[3];
    ptr2[i] = new int[3];
}

ptr1[0][0] = 1;
ptr1[0][1] =2;
ptr1[0][2] =2;
ptr1[1][0] =4;
ptr1[1][1] =5;
ptr1[1][2] =6;
ptr1[2][0] =7;
ptr1[2][1] =8;
ptr1[2][2] =9;

ptr2[0][0] = 1;
ptr2[0][1] =2;
ptr2[0][2] =2;
ptr2[1][0] =4;
ptr2[1][1] =5;
ptr2[1][2] =6;
ptr2[2][0] =7;
ptr2[2][1] =8;
ptr2[2][2] =9;

cout << equal(ptr1,ptr2,3,3);

return 0;

}

CodePudding user response:

Your initial call of the equal function is

equal(ptr1,ptr2,3,3)

That passes the size of the matrix as the row and col arguments, not the top indexes which is what the function expects.

That means when you do e.g. matrix1[row][col] you will go out of bounds and have undefined behavior.

Either change your logic in the function to always subtract one from the row and col values. Or (much simpler) change the initial call to use the top index instead of the size:

equal(ptr1,ptr2,2,2)

CodePudding user response:

This is a common mistake in the C language, that is, the index of the array always start from 0, which also means that the upper limit index of the array is always 1 less than your intuitive size. For example, if you have a one-demensional array, just like int arr[35], how should you get the last element? The correct answer is arr[34], not arr[35], which will bring an out-of-bounds error. So back to your question, very obviously you made a mistake.

  • Related