[英]C programming transpose matrix, #define
你能幫我嗎,我有問題。 這是轉置矩陣的程序。 當行數或列數等於357或更大的程序不起作用時(定義MAX_n 357,定義MAX_m 357)。 當小於357時程序正常工作。
#include <stdio.h>
#include <stdlib.h>
#define MAX_m 357
#define MAX_n 357
void main()
{
int a[MAX_m][MAX_n],b[MAX_m][MAX_n];
int r=0,j,i;
printf("\nProgram to transpose matrix\n");
for(i=0;i<MAX_m;i++)
{
for(j=0;j<MAX_n;j++)
{
r=rand();
a[i][j]=r;
}
}
printf("\nMatrix A: ");
for(i=0;i<MAX_m;i++)
{
printf("\n");
for(j=0;j<MAX_n;j++)
{
printf(" ");
printf("%d",a[i][j]);
}
}
for(i=0;i<MAX_m;i++)
{
for(j=0;j<MAX_n;j++)
{
b[i][j]=a[j][i];
}
}
printf("\nResultant Matrix: ");
for(i=0;i<MAX_m;i++)
{
printf("\n");
for(j=0;j<MAX_n;j++)
{
printf(" ");
printf("%d",b[i][j]);
}
}
printf("\n");
return(0);
}
正如其他人在評論中指出的那樣,這一定是內存分配問題。 在Unix上,您可以檢查Bash shell中的ulimit -s
以了解您的堆棧大小限制,或在tcsh中limit stack
。
由於這看起來像是家庭作業,因此我將把它留給您和您的老師,以討論不同的內存分配策略。
PS,將來指出您遇到的故障類型會有所幫助,而不是僅僅指出“它沒有用”。
我用C ++完成,創建了一個Matrix類。 您可以由此輕松地在C語言中進行制作。 我知道二維數組似乎更易於理解(在轉置時),但是它們只是將它們寫下來的一種便捷方式(有一點開銷),並且是等效的。 您還可以查看此代碼的效率。
#include <iostream>
#include <time.h>
using namespace std;
void print_array(int * A, int rows, int cols);
class Matrix{
int rows, cols;
int *A;
public:
Matrix(){};
Matrix (int *A, int rows, int cols): rows(rows), cols(cols) {
this->A = A;
};
Matrix transpose(){
int* T;
T = new int[rows*cols];
int rows_T(this->cols);
int cols_T(this->rows);
for(int i=0;i<rows_T;++i){
for (int j=0;j<cols_T;++j){
T[i*cols_T+j] = this->A[j*cols+i]; //T[i][j]=A[j][i]
}
}
return Matrix(T, rows_T, cols_T);
};
void print(){
for (int i=0;i<rows;++i){
for(int j=0;j<cols;j++){
cout<<A[i*cols+j]<<" ";
}
cout<<" "<<endl;
}
}
};
void print_array(int * A, int rows, int cols){
for (int i=0;i<rows;++i){
for(int j=0;j<cols;j++){
cout<<A[i*cols+j]<<" ";
}
cout<<" "<<endl;
}
}
int main(){
clock_t t;
t= clock();
int rows(2000), cols(1000);
int *A = new int[rows*cols];
for(int i=0;i<rows*cols;++i){
A[i]= rand() %10;
}
Matrix M1(A, rows, cols);
Matrix B;
B = M1.transpose();
t = (clock()-t);
cout<<"took (seconds): "<<t/1000000.0 <<endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.