### Anyone can help me fix my code?

The matrix is being allocated on the heap as it is defined as static. To allocate on the stack, don't define as static:

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758`` ``````#include using std::cin; using std::cout; constexpr int ROWS {4}; constexpr int COLS {4}; void displayMatrixContents(const int matrix[][COLS]) { cout << "Col\t1\t2\t3\t4\n"; cout << "------------------------------------\n"; for (int rows = 0; rows < ROWS; ++rows) { cout << "Row: " << rows + 1; for (int cols = 0; cols < COLS; ++cols) cout << "\t" << matrix[rows][cols]; cout << '\n'; } } bool searchNumberInMatrix(const int matrix[][COLS], int& row, int& col, int number) { for (int rows = 0; rows < ROWS; ++rows) for (int cols = 0; cols < COLS; ++cols) if (matrix[rows][cols] == number) { row = rows + 1; col = cols + 1; return true; } return false; } int main() { constexpr int matrix[ROWS][COLS] {{ 18, 39, 91, 91 }, { 67, 3, 9, 95}, { 69, 3, 68, 93}, { 69, 21, 92, 92}}; displayMatrixContents(matrix); cout << "\nEnter an integer: "; int number {}; cin >> number; int row {}; int col {}; if (searchNumberInMatrix(matrix, row, col, number)) cout << "\nFound " << number << " at " << "Row # " << row << " Col # " << col << '\n'; else cout << "\nNumber " << number << " was not found" << '\n'; }``````

 ``` Col 1 2 3 4 ------------------------------------ Row: 1 18 39 91 91 Row: 2 67 3 9 95 Row: 3 69 3 68 93 Row: 4 69 21 92 92 Enter an integer: 18 Found 18 at Row # 1 Col # 1 ```

Last edited on
Topic archived. No new replies allowed.