我使用以下C++代碼來執行矩陣乘法,並且它對SIZE = 500運行正常。但是,當SIZE = 600或更高時代碼將失敗。 (運行時錯誤)C++中的矩陣乘法給出運行時錯誤
我跑它Ideone.com 它。OUPUTS 「運行時錯誤時間:0記憶:3292信號:11」
,並在我的本地機器過它給我一個錯誤
#include <cstdlib>
#include<iostream>
#include <stdio.h>
#include <sys/time.h>
using namespace std;
class Timer {
private:
timeval startTime;
public:
void start(){
gettimeofday(&startTime, NULL);
}
double stop(){
timeval endTime;
long seconds, useconds;
double duration;
gettimeofday(&endTime, NULL);
seconds = endTime.tv_sec - startTime.tv_sec;
useconds = endTime.tv_usec - startTime.tv_usec;
duration = seconds + useconds/1000000.0;
return duration;
}
static void printTime(double duration){
printf("%5.6f seconds\n", duration);
}
};
using namespace std;
const int SIZE = 600; // for size*size matrix
void MultiplyMatricesSequential(double a[][SIZE],double b[][SIZE],double ans[][SIZE]);
int i,j,k;
double s;
/*
*
*/
int main(int argc, char** argv) {
double a[SIZE][SIZE], b[SIZE][SIZE], ans[SIZE][SIZE];
// assign the numbers for matrix a and b
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
a[i][j]=(double)rand()/RAND_MAX;
b[i][j]=(double)rand()/RAND_MAX;
}
}
MultiplyMatricesSequential(a,b,ans);
return 0;
}
void MultiplyMatricesSequential(double a[][SIZE],double b[][SIZE],double ans[][SIZE])
{
Timer timer = Timer();
timer.start();
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
for (k = 0; k < SIZE; k++)
s += a[i][k] * b[k][j];
ans[i][j] = s;
s = 0.0;
}
}
double duration = timer.stop();
cout << "Sequential Method time elapsed for SIZE " << SIZE << " : ";
timer.printTime(duration);
}
那麼我在這裏做錯了什麼?
注意: 當不使用定時器時它仍然是相同的。所有的
#include <cstdlib>
#include<iostream>
#include <stdio.h>
#include <sys/time.h>
using namespace std;
const int SIZE = 500; // for size*size matrix
void MultiplyMatricesSequential(double a[][SIZE],double b[][SIZE],double ans[][SIZE]);
int i,j,k;
double s;
/*
*
*/
int main(int argc, char** argv) {
double a[SIZE][SIZE], b[SIZE][SIZE], ans[SIZE][SIZE];
// assign the numbers for matrix a and b
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
a[i][j]=(double)rand()/RAND_MAX;
b[i][j]=(double)rand()/RAND_MAX;
}
}
MultiplyMatricesSequential(a,b,ans);
return 0;
}
void MultiplyMatricesSequential(double a[][SIZE],double b[][SIZE],double ans[][SIZE])
{
for (i = 0; i < SIZE; i++) {
for (j = 0; j < SIZE; j++) {
for (k = 0; k < SIZE; k++)
s += a[i][k] * b[k][j];
ans[i][j] = s;
s = 0.0;
}
}
}
我猜你用完了內存。 – duffymo 2014-09-19 20:56:17
所以我不能乘以600 * 600大小的兩個矩陣:( – prime 2014-09-19 20:57:21
)你不能在棧上聲明三個600x600'double'數組(自動存儲)。 – Blastfurnace 2014-09-19 20:59:00