1

在下面的代码中,我想在结构中包含第三个维度。结构基因型和其余标识符已经定义。这没有问题:

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]); 
      }
    }   
  }

对于第三个维度,我尝试了以下方法:

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

对于 (w=0; w< numFiles; w++){

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

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 回答