Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C++
 #include<iostream>
using namespace std;
class wave
{
public:
  void initialdata(double **,int ,int);
  void solveFD(double **,double *,double *,double ,double ,double,int,int );
};
void wave::initialdata(double **u,int nx,int nt)
{
  int i,j;
  for (j=1;j<nt;j++)
    for (i=1;i<nx;i++)
    {
      if(i<=20) 
      {
        u[i][j]=2.0;
      }
      else {u[i][j]=1.0;}
   }
}
//
void wave::solveFD(double **u,double *x,double *t,double  c,double dt,double dx,int nx,int nt)
{
  int i,j;
  for(j=1;j<nt;j++)
    for (i=1;i<nx;i++)
    {
      x[i]=(i-1)*dx;
      t[j]=(j-1)*dt;
      u[i][j+1]=u[i][j]-(c*dt/dx)*(u[i+1][j]-u[i][j]);
    }
}
//
int main()
{
  int i,j;
  int numx=101,numt=101;
  double  cvalue=1.0;
  double **umatrix,*xmatrix,*tmatrix,dtval,dxval;
  dtval=1.0/(numt-1);
  dxval=1.0/(numx-1);
  umatrix=new double *[numx+1];
  xmatrix=new double [numx+1];
  tmatrix=new double [numt+1];
  for (i=1;i<numt;i++)
  {
    umatrix[i]=new double [numt+1];
  }
  wave wave1;
  wave1.initialdata(umatrix,numx,numt);
  wave1.solveFD(umatrix,xmatrix,tmatrix,cvalue,dtval,dxval,numx,numt);
  for (j=1;j<numt;j++)
    for (i=1;i<numx;i++)
    {
      cout<<umatrix[i][j];
    }
  for (i=1;i<numt;i++)
  {
    delete umatrix[i];
  }
  delete umatrix,xmatrix,tmatrix;
  return 0;
}
Posted
Updated 4-Aug-15 20:54pm
v3

1 solution

As Ujesh Mohanan, noted, my previous soulution was wrong, since you actually allocated the matrix. However you forgot the last item:



C++
for (i=1;i<numt;i++)
 {
   umatrix[i]=new double [numt+1];
 }



Should be instead
C++
for (i=1;i<=numt;i++)
  {
    umatrix[i]=new double [numt+1];
  }




Again, I strongly suggest you using std::vector<double> instead with messing with raw pointers.

By the way:
Quote:
delete umatrix,xmatrix,tmatrix;

is wrong.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900