以下は、私が VS2008 で書いた 2 つのサンプル コードです。最初のサンプル コードは正常に動作しますが、(ツリーの) 2 番目のサンプル コードではエラーが発生します。
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;
}
2 番目のプログラムで、その場所を指すことができないのはなぜですか?
編集:実行時に発生したエラーは次のとおりです。
test.exe の 0x004114b4 で未処理の例外: 0xC0000005: アクセス違反の読み取り場所 0x000000004。
中断 継続 無視