以下是我在 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;
}
为什么在第二个程序中它不能指向那个位置?
编辑:我在运行时遇到的错误是:
test.exe 中 0x004114b4 处未处理的异常:0xC0000005:访问冲突读取位置 0x000000004。
中断继续忽略