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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>

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.