Can you help me, I have a problem. This is program that transpose matrix. When is number of rows or columns equals 357 or bigger program doesn't work (define MAX_n 357, define MAX_m 357). When is less than 357 program works normally.
#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);
}
As others have stated in comments, this has to be a memory allocation problem. On Unix, you can check ulimit -s
in the Bash shell for your stack size limit, or limit stack
in tcsh.
Since this looks like homework, I'll leave it to you and your teacher for a discussion on different memory allocation strategies.
PS, it would be helpful in the future to indicate what type of failure you're experiencing, as opposed to just "it didn't work".
I did it in C++, I created a class Matrix. You could easily make it in C from this. I know two-dimensional arrays seem easier to understand (when transposing) but they are simply a convenient way to write them down (with a little overhead) and are equivalent. You can also see how efficient this code is.
#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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.