-1

我有一个数组 c[7][8](或 c[56])。我必须将数组的 8 个元素传递给一个函数(在不同的类中)7 次。从这个函数,我再次必须将它传递给另一个函数。我试过的是

int main(){
...
double a[]={2.1,2.2,2.3,....};//7 elements
double b[]={1.1,1.2,1.3,....};//8 elements
double c[]={0.5,0.0,0.4,....};//56 elements. I actually want to use c[7][8]; but I thought c[56] would be easier
for (int i=0; i<7; i++){
  classa.calc(a[i],b[i],&c[i*8]); //assuming I use the 1D array for c. I don't want to pass the array a and b, but ith element.
  //for c, I want to pass 8 consecutive elements of c each time i call the function like c[0-6],c[7-13] etc
}
}

a 和 b 是两个不同的数组,我必须在函数中使用 element(i) 。

现在,在课堂上:

class classa{
void function(double* c, double* r) {
  ...
for (int i=0; i<8; i++) c[i]=h*c[i]*pow(x,i));//here an algorithm is used to get the new value of c as an existing function of c. the given function is just a part of the algorithm.
for (int j=0; j<N1; j++)  r[j]=some function of c;

}
public:
//here I want c to be used as a 1D array of 8 elements. same in function too
...
void calc(double a, double b, double* c){ 
  function(&c[0]);
...
}
};

当我运行程序时,我只得到前 8 个元素的结果,并且给出了分段错误。我如何解决它?

4

2 回答 2

0

其实array[n][m]不是array[n * m]。您可以a[n * m]用作替代品b[n][m],但具有正确的索引功能:

b[i][j] == a[i * ROW_SIZE + j];

其实&c[0] == c&c[i * 8] == c + i * 8

在您的代码中,我看到两个常量7N1. 你能检查一下N1是否与7. 我假设你可以在这里越界:

for (int j=0; j<N1; j++)  r[j]=some function of c;
于 2012-08-22T11:34:38.333 回答
0

根据更新回答

看起来你有更多的逻辑错误。您的循环应该在函数中从 i=0 运行到 8(8 次而不是 7 次)。而且我还假设您正在创建一个实例classa否则创建一个。

 class classa{
    void function(double* c) {
      ...
    for (int i=0; i<8; i++)
        c[i]=h*c[i]*pow(x,i);    
    }
    public:
    //here I want c to be used as a 1D array of 8 elements. same in function too
    ...
    void calc(double a, double b, double* c){ 
      function(c);
    ...
    }
    };

旧答案

由于您试图通过 &c[i][0] 七次。这应该足够了(assumming c is double**)。

for (int i=0; i<7; i++)
{
   classa.calc(a[i],b[i],c[i]); //This is equal to &c[i][0] or *(c+i)
}

并进一步更改function(&c[0]);function(c[0]);因为c[0] is already double*在这里学习

void calc(double a, double b, double* c)
{
    function(c[0]);
    //Update with Question 
    //You are using wrong overload, it should be something like this:-> 
    function(c[0],&a);//or &b whichever applicable.
 ... 
}
于 2012-08-22T11:29:29.243 回答