2014-11-21 39 views
0

IM以下洛雷娜芭芭拉博士的12個步驟,以納維 - 斯托克斯方程(http://lorenabarba.com/blog/cfd-python-12-steps-to-navier-stokes/)結構,但我不知道怎麼做二維線性對流。我想知道如果有人在這裏會熟悉如何做到這一點。 下面是我的示例代碼:二維線性對流++(分段錯誤)

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cstring> 
#include <cstdlib> 
#include <typeinfo> 
#include <sstream> 
#include <cmath> 

void linspace_2d(double a, double b, double c, double d, double ** array){ 
    double delta =(b-a)/(c-1); 
    for (int i=0; i<c; ++i){ 
      for (int j=0; j<d; ++j){ 
        array[i][j]= j*delta; 
       } 
     } 
    } 

void convection_2d(const std::string& str, const int nx, const int ny, const int nt){ 
     double c=1.;   // speed 
     double dx=2.0/(nx-1.); // grid distance in x direction 
     double dy=2.0/(ny-1.); // grid distance in y direction 
     double sigma=0.2; 
     double dt=sigma*dx;  // time step 

     double **space;   // mesh grid 
     // Alocate memory 
     space = new double *[nx]; 
     for (int i=0; i<nx; ++i){ space[i] = new double[ny]; } 

     double a=0, b=2; 
     linspace_2d(a, b, nx, ny, space); // function creates gives values to the mesh 

     // Initialize the array u and 
     double **u;  
     u = new double *[nx]; 
     for (int i=0; i<nx; ++i){ u[i] = new double[ny]; } 

     // Set inital conditions 
     for (int i=0; i<nx; ++i){ 
       for (int j=0; j<ny; ++j){ 
         u[i][j] = 1.; 
         if (((double) i>=0.5/dx) && ((double) i<(1./dx+1.)) && ((double) j>=0.5/dy) && ((double) j<(1./dy+1.))){ 
           u[i][j] = 2.; 
         } 
       } 
     // Iteration 
     for (int t=0; t<nt; ++t){ 
       // Copy elements of array u into array un 
       double **un; 
       un = new double *[nx]; 
       for (int x=0; x<nx; ++x){ un[x] = new double[ny]; } 
       for (int x=0; x<nx; ++x){ 
         for (int y=0; y<ny; ++y){ 
           un[x][y] = u[x][y]; 
         } 
       } 

       // take timestep 
       for (int i=0; i<nx; ++i){ 
         for (int j=0; j<ny; ++j){ 
           u[i][j] = un[i][j] - (c*dt/dx*(un[i][j] - un[i-1][j])) - (c*dt/dy*(un[i][j]-un[i][j-1])); 

         } 
       } 
     } 
+0

這不是Python ...請刪除標籤。 – 2014-11-21 22:05:07

+0

這不是Java。如果你寫'new',那麼你必須寫'delete'。 – 2014-11-21 22:27:22

+1

C++提供了比原始C風格數組更好的容器('std :: vector'),相信我,您將避免通過學習如何使用它們來減少數小時。 – kebs 2014-11-21 22:47:36

回答

1

訪問un[i-1][j]un[i][j-1]分別當i == 0j == 0超出陣列界,因此崩潰。

而且您泄漏大量分配un每次循環記憶,永不刪除。