在下面的代码中,我想在结构中包含第三个维度。已经定义了结构基因型和其余标识符。 这没有问题:
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 * *));
for(w = 0; w&lt; 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]);
}
}
}
}
但是这给了我一个分段错误。
你介意告诉我如何避免这种分段错误吗? 任何帮助将非常感谢。
提前感谢您的回复!!!
答案 0 :(得分: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;