Reputation: 85
I have this code :
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;
}
When the matrix X is 7x2 or 5x2, the program it's ok. When the matrix X is 8x2 or 6x2 the program doesn't print the message "That's ok 2". I realize something is wrong with the structure(specifically in the command
tree->vp.coordinates=(double *)malloc(d*sizeof(double))
) but I cannot fix it. Do you have any ideas;
Upvotes: 1
Views: 56
Reputation: 12732
struct vptree *tree;
printf("That 's ok! 1\n");
tree->vp.coordinates=(double *)malloc(d*sizeof(double));
tree
is not pointing to valid memory that is the reason you have undefined behavior when you dereference it.
Maybe you first need to allocate memory to it and free
it later.
struct vptree *tree = malloc(sizeof *tree);
…
free(tree);
or declare it as normal variable.
struct vptree tree;
// access it using (.) operator
tree.vp.coordinates=(double *)malloc(d*sizeof(double));
Upvotes: 5