1

次のコードでは、構造に 3 番目の次元を含めたいと思います。構造の遺伝子型と残りの識別子は既に定義されています。これは問題なく動作します:

struct genotype ** populationrows = (struct genotype **) calloc(MAXGENS, sizeof(struct genotype *));

  for (k=0; k< MAXGENS; k++) {

    populationrows[k]= (struct genotype *) calloc (POPSIZE, sizeof (struct genotype));  

    for (j=0; j<2; j++) {
      for (i=0; i<3; i++) { 
        populationrows[k][j].fitness = 0;
        populationrows[k][j].rfitness = 0;
        populationrows[k][j].cfitness = 0;
        populationrows[k][j].lower[i] = 1.0;
        populationrows[k][j].upper[i]= 2.0;
        populationrows[k][j].gene[i] = 3.0;
        printf(" populationrows[%u][%u].gene[%u]=%25lf \n", k,j,i,populationrows[k][j].gene[i]); 
      }
    }   
  }

そして、3次元については、次のことを試しました。

構造体遺伝子型 * **人口行 = (構造体遺伝子型 * **) calloc(numFiles, sizeof(構造体遺伝子型 * *));

for (w=0; w< numFiles; w++){

populationrows[w]= (構造体遺伝子型 **) calloc (MAXGENS, sizeof (構造体遺伝子型 *));

for (k=0; k<MAXGENS; k++) {    
  for (j=0; j<2; j++) {
    for (i=0; i<3; i++) {   
      populationrows[w][k][j].fitness = 0;
      populationrows[w][k][j].rfitness = 0;
      populationrows[w][k][j].cfitness = 0;
      populationrows[w][k][j].lower[i] = 1.0;
      populationrows[w][k][j].upper[i]= 2.0;
      populationrows[w][k][j].gene[i] = 3.0;
      printf(" populationrows[%u][%u][%u].gene[%u]=%25lf \n", w,k,j,i,populationrows[w][k][j].gene[i]); 
    }
  }     
 }  
}

しかし、これによりセグメンテーション違反が発生します。

このセグメンテーション違反を回避する方法を教えていただけませんか? どんな助けでも大歓迎です。

お返事ありがとうございます!!!

4

1 に答える 1

0

Cだと仮定します。

データへのポインターを指すポインターの配列の代わりに、フラットな配列を使用することをお勧めします。そんな感じ:

int n_w = 42, n_k = 23, n_j = 423; // size of dimensions

struct genotype * population = (struct genotype *) calloc(n_w * n_k * n_j, sizeof(struct genotype));

次に、要素 (10, 11, 12) を取得しています:

population[10 * n_k * n_j + 11 * n_j + 12].fitness = 0;

それを関数に入れると、きれいになります:

int n_w = 42, n_k = 23, n_j = 423; // size of dimensions

struct genotype * create_array() {
    return (struct genotype *) calloc(n_w * n_k * n_j, sizeof(struct genotype));
}

struct genotype * get_element(int w, int k, int j) {
    return &population[w * n_k * n_j + k * n_j + j];
}

// ...

struct genotype * population = create_array();

get_element(10, 11, 12)->fitness = 0;
于 2013-02-17T10:58:18.760 に答える