다음은 VS2008에서 작성한 두 가지 샘플 코드입니다. 첫 번째 샘플 코드는 잘 작동하지만 두 번째 (트리의) 코드는 오류가 발생합니다.트리 프로그램의 오류는 어디에 있습니까?
1)
#include<iostream>
using namespace std;
struct node{
int number;
struct node *right;
struct node *left;
}nodeType;
int insert(struct node *,int);
int main(){
struct node * root=(struct node *)malloc(sizeof(node));
root->left=NULL;
root->right=NULL;
root->number=10;
insert(root,100);
cout<<root->right->number; //This works fine
return 1;
}
int insert(struct node * leaf,int data){
leaf->left =(struct node *)malloc(sizeof(node));
leaf->right =(struct node *)malloc(sizeof(node));
struct node *temp = leaf;
temp->right->number=12;
temp->left->number=11;
temp->right->right=NULL;
temp->right->left=NULL;
temp->left->left=NULL;
temp->left->right=NULL;
return 1;
}
2)
#include<iostream>
using namespace std;
struct node{
int number;
struct node *right;
struct node *left;
}nodeType;
int insert(struct node *,int);
int main(){
int data[50];
int i;
for(i=0;i<50;i++){
data[i]=rand()%100;
}
struct node * root=(struct node *)malloc(sizeof(node));
root->left=NULL;
root->right=NULL;
root->number = 36;
for(i=0;i<50;i++){
insert(root,data[i]);
}
cout<<root->right->number; //This doesn't work, and it throws some memory error. Though it assigns a value(it is 41) which goes to the right side in the insert function, the root's right side pointer is not able to point into that memory location. Similar case with root->.... also.
return 1;
}
int insert(struct node * leaf,int data){
if(leaf==NULL){
leaf = (struct node *)malloc(sizeof(node));
leaf->number=data;
leaf->left=NULL;
leaf->right=NULL;
}
else if(data>=leaf->number){
insert(leaf->right,data);
}
else if (data<leaf->number){
insert(leaf->left,data);
}
else
{
}
return 1;
}
왜 두 번째 프로그램에서 해당 위치를 가리킬 수 없습니까?
편집 : 내가 런타임 중에있어 오류가이었다가 0xc0000005 : TEST.EXE에서 0x004114b4에서
처리되지 않은 예외 액세스 vioation 위치를 읽는 0x000000004.
중단 계속 무시
당신은 PRNG를 시드하지 않습니다. 값으로 패스 포인터 매개 변수를 삽입하고 검색 할 필요가 없습니다! – alexbuisson
"약간의 오류를 준다"는별로 도움이되지 않습니다. "일부 오류"에 대한 세부 사항을 알려주십시오 - 컴파일 오류 또는 런타임 오류입니까? 또한 정확한 오류 메시지를 복사하여 붙여 넣으십시오. –
Q :'insert()'(마지막 것)은 어떻게 생각합니까? (힌트 : 당신의 나무에 노드를 삽입하지 않는다.) A : 메모리가 누수됩니다. 당신의 잎 매개 변수를보십시오. 값을 가리키는 포인터를 전달하므로 'leaf = ...'는 ... * 아무것도하지 않습니다. (누설하려는 메모리에 일시적으로 액세스 할 수있는 장소는 제외하고 VS2008을 실행하고 있습니다. ** * 디버거 사용 *** – WhozCraig