please proofread the code to avoid memory leak

can you just check if 'delete' is in the right place, please. i'm afraid of doind it wrong and having troubles after

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
  #include <iostream>
#include <ctime>
 
int main() {
    srand(time(NULL));
 
    int size;
    long long int product (1);
    
    std::cout << "matrix size = ";
        std::cin >> size;
    
    // std::cout << "Введите матрицу " << size << "x" << size << ":" std::endl;
    int **arr = new int*[size];
    for (int i = 0; i < size; i++) {
        arr[i] = new int[size];
        for (int j = 0; j < size; j++) {

            //cin >> arr[i][j]; // раскомментировать для ввода с консоли и
                                // нижнюю строку убрать
            arr[i][j] = rand() % 11 - 5; // [-5, 5]
            
            std::cout << arr[i][j] << "\t";
            
            // ниже побочной и выше главной
            if (i + j > size - 1 && j > i) {
                product *= arr[i][j];
            }
        }
        std::cout << std::endl;
    }
 
    std::cout << "Произведение элементов над главной и под побочной диагоналях = " 
        << product << std::endl; 
    
    for(int i = 0; i < size; i++) {
        delete[] arr[i];
    }
    delete[] arr;
    
    return 0;
}
Last edited on
yes, it looks good.

it is a lot faster and easier to do this in 1-d, though.
arr = new int[rows*columns];
arr[desired_row * columns + desired column] is the same as arr[row][col] in 2-d.
delete[] arr;

it is significantly better to use vectors, which handle the memory for you, if you can.
also, valarray is under-used and has a ton of cool tricks you can pull for matrix work.
Last edited on
Yes - you delete in the right order.

Note that if arr[i][j] == 0 at any time (the range is -5 to 5) , then the resultant product will be 0 irrespective of any of the other values.

This doesn't need arrays or vectors:

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
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>

int main() {
    std::srand(std::time(nullptr));

    std::cout << "matrix size = ";
    int size;
    std::cin >> size;

    long long product = 1;
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            int x = std::rand() % 11 - 5; // [-5, 5]
            std::cout << std::setw(2) << x << ' ';
            if (i + j > size - 1 && j > i)
                product *= x;
        }
        std::cout << '\n';
    }
 
    std::cout << "Произведение элементов над главной и под побочной диагоналях = " 
              << product << '\n';
}

thank you all so much, i'll be taking notes!:)
Topic archived. No new replies allowed.