通过指向函数的指针循环传递数组的一部分

时间:2012-08-22 11:18:55

标签: c++ arrays pointers

我有一个数组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是两个不同的数组,我必须在函数中使用元素(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个元素集的结果,并给出了分段错误。我该如何解决?

2 个答案:

答案 0 :(得分: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);
    ...
    }
    };

旧答案

因为你试图传递&amp; 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*Learn Here

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.
 ... 
}

答案 1 :(得分: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;