What is the best way to declare c++ 2d arrays which can have a less effect from the fixed and limited stack size. I recently got segmentation fault due to stackoverflow in following code. How does vectors tackle this issue?
Here is the code which I developed.
#include <iostream>
#include <stdlib.h>
using namespace std;
void printMatrix(double *mat);
void generateMat(double *mat);
void multiplyMat(double *a,double *b,double *c);
int n;
int start_s;
// the code you wish to time goes here
int stop_s;
int main(){
for(int i=500;i<1000;i++){
cout<< "Enter n:";
//cin >> n;
n=i;
cout<< "n="<<n<<endl;
double a[n][n],b[n][n],c[n][n]; //c = a * b, c is the
// result matrix
generateMat(*a);
generateMat(*b);
// initializing c matrix with 0s'
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
c[i][j]=0;
}
}
cout<<"Matrix 1"<<endl;
//printMatrix(*a);
cout<<endl<<"Matrix 2"<<endl;
//printMatrix(*b);
multiplyMat(*a,*b,*c);
cout<<endl<<"Result Matrix"<<endl;
//printMatrix(*c);
cout << endl<<"Execution time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << endl;
}
return 0;
}
void multiplyMat(double *a,double *b,double* c){
start_s=clock();
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
for(int k=0;k<n;k++){
*(c+i*n+j)+=(*(a+i*n+k)) * (*(b+k*n+j));
}
}
}
stop_s=clock();
}
void printMatrix(double *mat){
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
cout<< *(mat+i*n+j)<< " ";
}
cout<<endl;
}
}
void generateMat(double *mat){
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
*(mat+i*n+j)=(double)rand()/RAND_MAX*10;
}
}
}
Your matrices are using space on the local call stack (which is often limited to one, or a few, megabytes).
You should consider making a class
for them, which uses heap allocated data (and release it in the destructor). This answer is for C, not C++, but should be inspirational (just recode it in genuine C++, perhaps using smart pointers and/or some C++ standard container[s]).
You might represent a matrix with some internal std::vector data, and provide operations (i.e. member functions) to resize that matrix and access or modify its element of indices i & j