gpt4 book ai didi

c - 尝试将两个尺寸为 1000*1000 的大矩阵相乘会导致段错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:46:32 25 4
gpt4 key购买 nike

<分区>

尝试将维度为 1000*1000 的两个矩阵相乘。但是,尝试这样做会导致 Segmentation fault。可能是什么原因造成的,如何解决?

#include <stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
clock_t t;
t = clock();
long int a[1000][1000], b[1000][1000], result[1000][1000], r1=1000, c1=1000, r2=1000, c2=1000, i, j, k;

// Column of first matrix should be equal to column of second matrix and
/* while (c1 != r2)
{
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
}
*/

// Storing elements of first matrix.
printf("\nEnter elements of matrix 1:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
a[i][j]=rand()%20;
}

// Storing elements of second matrix.
printf("\nEnter elements of matrix 2:\n");
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
b[i][j]=rand()%20;
}

// Initializing all elements of result matrix to 0
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
result[i][j] = 0;
}

// Multiplying matrices a and b and
// storing result in result matrix
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
result[i][j]+=a[i][k]*b[k][j];
}
// Displaying the result
printf("\nOutput Matrix:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
printf("%ld ", result[i][j]);
if(j == c2-1)
printf("\n\n");
}
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds

printf("\n \nfunction took %f seconds to execute \n", time_taken);
return 0;
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com