Reputation: 21
I am trying to get two matrices with randomly generated numbers to multiply together but i keep getting segmentation fault and idk how to allocate the memory properly.
any help with this would be great
//here is the code
#include<iostream>
#include<iomanip>
#include<stdlib.h>
#include<stdio.h>
#include<ctime>
using namespace std;
int main()
{
srand (1023);
int a[1000][1000], b[1000][1000], mult[1000][1000], r1, c1, r2, c2, i, j, k;
cout << "Enter rows and columns for first matrix: ";
cin >> r1 >> c1;
cout << "Enter rows and columns for second matrix: ";
cin >> r2 >> c2;
while (c1!=r2)
{
cout << "Error! column of first matrix not equal to row of second.";
}
cout << endl << endl;
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
cout<<"mult["<<i<<"]["<<j<<"]: "<<rand()%9+1<<" "; //random matrix 1
}
cout << endl<< endl;
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
cout<<"mult["<<i<<"]["<<j<<"]: "<<rand()%9+1<<" "; //random matrix 2
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
mult[i][j]=rand()%9+1;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
mult[i][j]+=a[i][k]*b[k][j]; //matrix multiplication
}
cout << endl << "Output Matrix: " << endl;
clock_t begin = clock();
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
cout << " " << mult[i][j];
if(j==c2)
cout << endl;
clock_t end = clock();
double elapsed_secs = double(end-begin)*100;
cout<<"Elapsed Time: "<<elapsed_secs<<" milliseconds\n";
return 0;
}
Upvotes: 1
Views: 1943
Reputation: 1902
You are trying to create more than 11 MB in your current stack.
array[1000][1000] = 4 * 1000 * 1000 bytes = 4000000
You are creating in total 12000000 bytes for 3 arrays alone.
Try reducing the size of the array (or) get the size of the matrix and try to create the array in heap using new.
Check your stack size, it should be 8 MB
ulimit -a | grep stack
This is how you do for heap since you want 1000 to 5000
int** a = new int*[r1];
for(int i = 0; i < r1; ++i)
{
a[i] = new int[c1];
}
a[0][0] = 10;
std::cout << a[0][0] << std::endl;
// Delete all the columns
for(int i = 0; i < r1; ++i)
delete[] a[i];
delete []a ;
Also make sure you add values to a[][] and b[][], now you just do cout and print the values in the first 2 for loops and I suppose those should be in a[][] and b[][]
Upvotes: 1