0

前几天我试图用 C++ 编写一个矩阵操作程序。我首先创建了一个可以工作的矩阵容器。然后我尝试编写一个转置矩阵的函数。那是我遇到麻烦的时候。使用该函数会导致我的程序崩溃。

struct imat //matrix of integer numbers
{
friend int size(imat,int);
protected:
  const int nrows; const int ncols; //ncols = number of columns, nrows = number of rows
  int* mat; //internal array that holds the data
public:
  imat(const int m, const int n): nrows(m), ncols(n) //constructor
  {
    mat = new int[m*n]; //creates an array of size nrows*ncols
    for (int k=0; k<m*n; k++) mat[k]=0; //zeros all the elements
  }
  imat(const imat& src): nrows(src.nrows), ncols(src.ncols) //copy constructor
    {for (int k=0; k<nrows*ncols; k++) mat[k]=src.mat[k];} //copies the contents of src to this matrix
  imat& operator=(const imat& rhs) //assignment operator
  {
    if (nrows!=rhs.nrows||ncols!=rhs.ncols) throw(1); //lhs and rhs must have the same dimensions
    for (int k=0; k<nrows*ncols; k++) mat[k]=rhs.mat[k]; //copies the contents of rhs to this matrix (lhs)
    return *this; //return this matrix as output (lhs)
  }
  int& operator()(int i, int j) {return mat[(i-1)*ncols+(j-1)];} //A(i,j)=mat[(i-1)*ncols+(j-1)] (stores the matrix in the 1D array 'mat')
 ~imat() {delete[] mat;}
};

int size(imat mat, int dim) //gets matrix dimensions
{
  if (dim==1) return mat.nrows; //dimension 1 is number of rows
  if (dim==2) return mat.ncols; //dimernsion 2 is number of columns
  return 0; //returns 0 if dimesion number is invalid
}

imat trans(imat A)
{
  int m=size(A,1); //number of rows
  int n=size(A,2); //numbers of columns
  imat B(n,m); //creates an n*m matrix
  for (int i=1; i<=m; i++)
    for (int j=1; j<=n; j++)
      B(j,i)=A(i,j); //sets the components of B to the components of the transpose of A
  return B;
}

我尝试了以下主要功能,但它们都不起作用:

1)

int main()
{
  imat A(2,3);

  A(1,1)=11;
  A(1,2)=12;
  A(1,3)=13;
  A(2,1)=21;
  A(2,2)=22;
  A(2,3)=23;

  imat B = trans(A);

  return 0;
}

2)

int main()
{
  imat A(2,3);

  A(1,1)=11;
  A(1,2)=12;
  A(1,3)=13;
  A(2,1)=21;
  A(2,2)=22;
  A(2,3)=23;

  imat B(3,2)
  B = trans(A);

  return 0;
}

我的猜测是它与函数范围末尾的对象的破坏有关,尽管我不确定。请用简单的语言向我解释问题是什么以及如何解决它。

4

1 回答 1

2

您忘记在复制构造函数中为动态数组分配内存。您刚刚开始分配给mat[...],即使mat未初始化。

于 2013-11-13T16:24:40.727 回答