简体   繁体   中英

Segmentation fault (core dump) when creating a large 2d dynamic array using c++

Im trying to create a program that creates two 2d dynamic arrays and multiply them and give an output and calculate the time taken for the multiplication process based on the input size n. This code works when it comes to outputs lesser than 7 rows and 7 cols but gives an error when the number goes above 8.

using namespace std;

int m1c , m1r , m2c , m2r , i , j , k , l;

int** arr1 = new int*[m1c];
int** arr2 = new int*[m2c];
int** multArr = new int*[m1c];

int main(){

    cout << "Enter the Number of rows for matrix 1 :";
    cin >> m1c;

    cout << "Enter the Number of columns for matrix 1 :";
    cin >> m1r;

    cout << "Enter the Number of rows for matrix 2 :";
    cin >> m2c;

    cout << "Enter the Number of columns for matrix 2 :";
    cin >> m2r;

    for (i = 0; i < m1r; i++) {
        arr1[i] = new int[m1c];
        multArr[i] = new int[m1c];
    }

    for (i = 0; i < m2r; i++) {
        arr2[i] = new int[m2c];
    }

    if (m1r != m2c) {
        cout << "Number of rows in the first matrix must be equal to the numbr of columns in the second matrix ";
        return -1;
    }


    for (i = 0; i < m1r; i++) {
        for (j = 0; j < m2c; j++) {

            arr1[i][j] = rand() % 100;
        }
    }

    for (i = 0; i < m2r; i++) {
        for (j = 0; j < m2c; j++) {

            arr2[i][j] = rand() % 100;
        }
    }


    //Displaying the two arrays

    for (i = 0; i < m1r; i++) {
        for (j = 0; j < m1c; j++) {
            cout << arr1[i][j] << " ";
        }
        cout << endl;
    }

    cout << endl;

    for (i = 0; i < m2r; i++) {
        for (j = 0; j < m2c; j++) {

            cout << arr2[i][j] << " ";
        }
        cout << endl;
    }
    delete[] arr1;
    delete[] arr2;

    return 0;

}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Looks like an error initializing arr1. Your using m2c as the column count. You probably meant m1c.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM