gpt4 book ai didi

c - 通过指针从动态分配的二维数组中获取值

转载 作者:太空宇宙 更新时间:2023-11-04 03:03:51 25 4
gpt4 key购买 nike

我在一个函数中填充了一个动态分配的浮点多数组。

第二个函数必须利用指向前一个函数中定义的数组第一个元素的指针来获取数组的值。

第二个函数无法访问正确的内存位置,因此它不起作用,但如果以静态方式定义多数组,它就可以。

有人知道为什么吗?

eval_cell 应该获取 div_int 中定义的值

float f_imp(float x, float y){
return pow(x,2)+pow(y,2)-1;
}


int eval_cell(float* p){
int s[4];
s[0] = f_imp(*p, *(p+1)) <= 0;
printf("%f %f\n",*p, *(p+1));

s[1] = f_imp(*(p+3), *(p+4)) <= 0;
printf("%f %f\n",*(p+3), *(p+4));

s[2] = f_imp(*(p+9), *(p+10)) <= 0;
printf("%f %f\n",*(p+9), *(p+10));

s[3] = f_imp(*(p+6), *(p+7)) <= 0;
printf("%f %f\n",*(p+6), *(p+7));

printf("%d%d%d%d\n",s[0],s[1],s[2],s[3]);
return s[0];
}

void div_int(float* x1, float* y1,float* x2,float* y2,
float* f0, float* f2,float* f6,float* f8){
int i,j,m;
float* p;
float** a_cell; // array 9x3 contente coordinate vertici e valore funzione
*a_cell = (float**) malloc(9*sizeof(float*));
for (i=0;i<9;i++){
a_cell[i] = (float*) malloc(3*sizeof(float));
}
a_cell[0][0] = *x1;
a_cell[0][1] = *y1;
a_cell[0][2] = *f0;
a_cell[2][0] = *x2;
a_cell[2][1] = *y1;
a_cell[2][2] = *f2;
a_cell[6][0] = *x1;
a_cell[6][1] = *y2;
a_cell[6][2] = *f6;
a_cell[8][0] = *x2;
a_cell[8][1] = *y2;
a_cell[8][2] = *f8;
/*** calcolo dei valori incogniti di a_cell ***/
a_cell[1][0] = (*x1+*x2)/2;
a_cell[1][1] = *y1;
a_cell[1][2] = f_imp(a_cell[1][0], a_cell[1][1]);
a_cell[3][0] = *x1;
a_cell[3][1] = (*y1+*y2)/2;
a_cell[3][2] = f_imp(a_cell[3][0], a_cell[3][1]);;
a_cell[4][0] = (*x2+*x1)/2;
a_cell[4][1] = (*y2+*y1)/2;
a_cell[4][2] = f_imp(a_cell[4][0], a_cell[4][1]);
a_cell[5][0] = *x2;
a_cell[5][1] = (*y2+*y1)/2;
a_cell[5][2] = f_imp(a_cell[5][0], a_cell[5][1]);
a_cell[7][0] = (*x1+*x2)/2;
a_cell[7][1] = *y2;
a_cell[7][2] = f_imp(a_cell[7][0], a_cell[7][1]);

for (j=0;j<2;j++){
m = j*3;
for(i=0;i<2;i++){
m += i;
eval_cell(&a_cell[m][0]);
}
}
p = *a_cell;
for (i=0;i<9;i++){
for (j=0;j<3;j++){
printf("%f \n",*(p+3*i+j));
printf("%f \n",a_cell[i][j]);
printf("\n");
}
}
free(a_cell);
return;
}

最佳答案

这是因为你使用指针的方式不正确:请参阅 a_cell 是指向 9 个动态数组的指针,指向 3 个 float 的动态数组。所以当你执行 eval_cell(&a_cell[m][0]) (或者只是 eval_cell(a_cell[m]) 这实际上是一样的)你实际上得到了指向数组的指针3 花车。然后你做:

int eval_cell(float* p){

...
s[2] = f_imp(*(p+9), *(p+10)) <= 0;

*(p+9) 将得到 3 个 float 数组中的第 9 个元素,所以这是不正确的。

它以静态方式工作,因为内存中的静态多维数组只是一维数组,您为其提供了多索引(由编译器)。这就是为什么在静态中您可能会寻址有效的内存区域。

更多解释见图片: enter image description here

关于c - 通过指针从动态分配的二维数组中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8122320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com