-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) を使用する必要がある 2 つの異なる配列です。

さて、クラスで:

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

あなたのコードには、2つの定数7とが表示されN1ます。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まで実行されている必要があります(7回ではなく8回)。また、インスタンス作成していると仮定します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]を7回渡そうとしているので。これだけで十分です(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 に答える