이 코드가 있습니다.
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
역 참조 할 때 동작이 정의되지 않은 이유 인 유효한 메모리를 가리 키지 않습니다.
먼저 메모리를 할당 free
하고 나중에 할당해야 할 수도 있습니다 .
struct vptree *tree = malloc(sizeof *tree);
…
free(tree);
또는 일반 변수로 선언하십시오.
struct vptree tree;
// access it using (.) operator
tree.vp.coordinates=(double *)malloc(d*sizeof(double));
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다