gpt4 book ai didi

c - C中结构内部结构的问题

转载 作者:太空宇宙 更新时间:2023-11-04 00:56:40 24 4
gpt4 key购买 nike

我有这段代码:

struct node{
double *coordinates;
};

struct vptree{
struct node vp;
double md;
int idx;
struct vptree *inner;
struct vptree *outer;
};

void buildvp(double *X, int n, int d){

for(int i=0;i<n;i++){
for(int j=0;j<d;j++){
printf("%lf ",X[i*d+j]);
}
printf("\n");
}
struct vptree *tree;
printf("That 's ok! 1\n");
tree->vp.coordinates=(double *)malloc(d*sizeof(double));
printf("That 's ok! 2\n");

for(int i=0;i<d;i++){
tree->vp.coordinates[i]=X[(n-1)*d+i];
printf("for i=%d the X= %lf",i,tree->vp.coordinates[i]);
}
}


int main(){
double X[8][2]={{2,5},{1,1},{0,0},{1,3},{2,5},{1,1},{-2,8},{6,-1}};
buildvp(&X,8,2);
return 0;
}

当矩阵X为7x2或5x2时,程序没问题。当矩阵 X 为 8x2 或 6x2 时,程序不会打印消息“That's ok 2”。我意识到结构有问题(特别是在命令中tree->vp.coordinates=(double *)malloc(d*sizeof(double))) 但我无法修复它。你有什么想法吗?

最佳答案

   struct vptree *tree;
printf("That 's ok! 1\n");
tree->vp.coordinates=(double *)malloc(d*sizeof(double));

tree 未指向有效内存,这就是您在取消引用时出现未定义行为的原因。

也许您首先需要为其分配内存,然后再释放

   struct vptree *tree = malloc(sizeof *tree);

free(tree);

或将其声明为普通变量。

   struct vptree tree;
// access it using (.) operator
tree.vp.coordinates=(double *)malloc(d*sizeof(double));

关于c - C中结构内部结构的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58660440/

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