Memory 三维结构的内存分配

Memory 三维结构的内存分配,memory,structure,Memory,Structure,在下面的代码中,我想在结构中加入第三个维度。结构基因型和其他标识符已经定义。 这样做没有问题: struct genotype ** populationrows = (struct genotype **) calloc(MAXGENS, sizeof(struct genotype *)); for (k=0; k< MAXGENS; k++) { populationrows[k]= (struct genotype *) calloc (POPSIZE, sizeo

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

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]); 
      }
    }   
  }
对于第三维度,我尝试了以下方法:

结构基因型***填充行=结构基因型***callocnumFiles,sizeofstruct基因型**

对于w=0;w populationrows[w]=结构基因型**calloc MAXGENS,结构基因型的大小*

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]); 
    }
  }     
 }  
}
但这给了我一个分割错误

你介意告诉我如何避免这个分割错误吗? 任何帮助都将不胜感激


提前感谢您的回复!!!

我假设是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;

如果使用三个间接级别,则还需要三个级别的分配。但是,请考虑用一个带有一些智能索引的平面数组来替换它。