### Saddle point- Class - Garbage value

Ques. To find saddle point of the matrix using classes

Doubt. The function display giving garbage value of the contents of matrix. Why?

Code :

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384`` ``````#include using namespace std; class Saddle { private: int matrix[3][3]; int rno; int cno; public: void display() { int i,j; for(i=0; i<3; i++) { for(j=0; j<3; j++) cout<>matrix[i][j]; } //for(i=0; i<3; i++) //{ //for(j=0; j<3; j++) ////cout<s.matrix[i][j]) { min_row = s.matrix[i][j]; col_index = j; } } cout<
Last edited on
hello there, i think the problem is on line 25.

 ``123456789101112131415161718`` ``````Saddle(int n) //not sure what n means. { int i,j; for(i=0; i<3; i++) { for(j=0; j<3; j++) cin>>matrix[i][j]; } //for(i=0; i<3; i++) //{ //for(j=0; j<3; j++) ////cout<
The question says that the 2d matrix is to be allocated space dynamically. The exact words are : A parameterised constructor which takes the size n (as parameter), allocates dynamic space for the array, and puts values in it from the keyboard. It also initializes the data members (b) and (c) above to a value -1, indicating that the saddle has not yet been determined.
n is size of square matrix. At the present I have fixed it to 3.

@Yolanda, you are right, the problem is of "matrix" overshadowing class variable. But I need to allocate memory dynamically for the array. What shall I do?
Last edited on
if that the case then all you need to do is not create a new variable

change line 7 to a pointer to pointer
 `` `` ``int **matrix = nullptr;/// i init matrix to a null pointer ``

change the constructor definition to.
 ``12345678910111213141516`` ``````Saddle(int n) :rno(-1),cno(-1) /// list initializers are prefered { int i,j; matrix = new int*[n]; for(i = 0; i>matrix[i][j]; } }``````

advice - now that you have decided to use dynamic memory, you also
have to handle it's de-allocation to avoid memory leak, you should
have a deconstructor `~Saddle()` defined
Last edited on
Topic archived. No new replies allowed.