2012-02-29 90 views
0

我有一個數組:通行證陣列作爲參數

int *BC_type_vel; 
BC_type_vel = new int [nBou+1]; 

和的函數:

void BC_update (const int type[], float X[]) { 

for (int i=1; i<=nBou; ++i) { 

    if (type[i] == 1) { 

     std::cout << i << " " << type[i] << " " << BC_type_vel[i] << std:: endl; 

     for (int e=PSiS[i]; e<PSiE[i]; ++e) {    

      X[e] = X[elm[e].neigh[0]]; 
     } 
    } 
} 

}

我稱其爲:

BC_update(BC_type_vel,U); 

它給輸出如:

1 1 0 
2 1 0 
3 1 0 
4 1 1 
5 1 0 

那麼爲什麼函數參數不能正確地複製值呢?

+2

請注意C中的數組從0開始(basemen + 0)。你在功能上進入假記憶。 – Edu 2012-02-29 22:30:45

+0

@Edu:這是一個非常奇怪的方式來遍歷一個數組,應該改變,但他實際上並沒有超過它。如果你看看數組是如何創建的,它有'nBou + 1'元素,它通過1循環到'nBou'。現在他並沒有向我們展示他是如何填充陣列的,所以我想這就是問題所在。我建議將它標記爲C,但在C++中,您應該只使用'vector'並讓您的生活更輕鬆。 – 2012-02-29 22:34:56

+0

@EdS。這是真的。他只是在浪費第一排,但沒有損傷記憶。我同意,這只是C,而不是C++ – Edu 2012-02-29 22:38:29

回答

1

我嘗試下面的代碼用gcc:

int *BC_type_vel; 
int nBou = 10; 

void BC_update (const int type[]) { 
    for (int i=1; i<=nBou; ++i) { 
     if (type[i] == 1) 
      std::cout << i << " " << type[i] << " " << BC_type_vel[i] << std:: endl; 
    } 
} 

int main() { 
    int i; 

    BC_type_vel = new int [nBou+1]; 
    for (i=1; i<=nBou; ++i) { 
     if (i%2 == 0) 
      BC_type_vel[i] = i; 
     else 
      BC_type_vel[i] = 1; 
    } 
    BC_update(BC_type_vel); 

    return 0; 
} 

,並給出了預期的結果:

1 1 1 
3 1 1 
5 1 1 
7 1 1 
9 1 1 

所以問題是別的地方在你的代碼。你需要提供給我們其餘的。