+ 2

Invalid types int[int] for array subscript. Searching in a matrix

I have been trying to do a binary search in a matrix and getting this error Here's the code #include <iostream> using namespace std; int count = 0; int search(int r, int c , int key , int * matrix){ int row=0; int col=c-1; while(row<c && col>=0){ if(count>0) break; if(matrix[row][col]==key){ cout<<"Key is at "<<row<<","<<col<<endl; count++; } else if(matrix[row][col]<key){ row++; } else{ col--; } } return -1; } int main(){ int r; // Get length of row from user cout<<"Enter the row number \n"; cin>>r; int c; // Get length of col from user cout<<"Enter the col number \n"; cin>>c; int matrix[r][c]; // a matrix is defined of r x c cout<<"Enter the values of matrix \n"; // Nested loop to get the value of matrix from user for(int i=0;i<r;i++) { for(int j=0;j<c;j++){ cin>>matrix[i][j]; } } int key; cin>>key; search(r,c,key,(int*)matrix); return 0; }

22nd Oct 2022, 3:39 PM
Utkarsh Shrivastava
Utkarsh Shrivastava - avatar
5 Antworten
+ 1
that's Inplace of matrix[row][col] in function.
22nd Oct 2022, 5:40 PM
Jayakrishna 🇮🇳
+ 3
Use pointer notation of accessing array elements as *((matrix+row*r)+col) ; Or Define function as const int M = 5; int search(int r, int cr, int key , int (*matrix)[M] ) { //.. } Call function as : search(r,c,key, matrix);
22nd Oct 2022, 5:25 PM
Jayakrishna 🇮🇳
+ 2
Thanks it worked 🙏 can you please explain what you did there..
22nd Oct 2022, 5:44 PM
Utkarsh Shrivastava
Utkarsh Shrivastava - avatar
+ 1
Sir can you guide me on which line I have to use the first solution?
22nd Oct 2022, 5:37 PM
Utkarsh Shrivastava
Utkarsh Shrivastava - avatar
+ 1
You are passing first array element address (int*)matrix; *(*(matrix+row)+col) is equal to martix[row][col]; in pointer notation. *((matrix+row*r) +col) here (matrix+row*r) will point to r'th row directly.. hope it helps..
22nd Oct 2022, 5:58 PM
Jayakrishna 🇮🇳