2012-02-29 93 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 

所以问题是别的地方在你的代码。你需要提供给我们其余的。