繁体   English   中英

C编程转置矩阵,#define

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM