随机数大于 1000 的矩阵乘法

Matrix multiplication with random numbers larger than 1000

本文关键字:大于 1000 随机数      更新时间:2023-10-16

我正在尝试让两个随机生成的数字矩阵相乘,但我不断遇到分割错误和 idk 如何正确分配内存。

对此的任何帮助都会很棒

这是代码

#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<<" millisecondsn";
return 0;
}

您正在尝试在当前堆栈中创建超过 11 MB。

数组[1000

][1000] = 4 * 1000 * 1000 字节 = 4000000

您仅为 3 个数组总共创建了 12000000 字节。

尝试

减小数组的大小(或)获取矩阵的大小,并尝试使用 new 在堆中创建数组。

检查您的堆栈大小,它应该是 8 MB

ulimit -a | grep stack

这就是你对堆的做法,因为你想要 1000 到 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 ;                     

还要确保将值添加到 a[][] 和 b[][],现在您只需执行 cout 并打印前 2 个 for 循环中的值,我想这些值应该在 a[][] 和 b[][] 中