我正在为学校的项目编写一个程序,要求我们根据从文件中读取的数据(在本例中为字符串)创建Binary Search Tree 。 当输入重复的字符串时,树应该通过递增整数值来允许重复。
TreeNode是一个结构如下:
struct TreeNode { string word; int count; TreeNode * left; TreeNode * right; };我遇到的问题是当我尝试调用插入函数时程序崩溃。 我运行调试器,我收到以下错误:
在Proj12.2.exe中0x00E2A87C抛出异常:0xC0000005:访问冲突读取位置0x00000014。
导致此错误的原因是什么? 以下是相关代码的其余部分:
TreeNode * Root = new TreeNode; Root->right = NULL; void insert(TreeNode *& root, string item) { //insert function, called by Root->right,temp if (root->word == item) { root->count++; return; } if (root == NULL && root->word != item) { root = new TreeNode; root->left = NULL; root->right = NULL; root->word = item; root->count = 1; return; } if (item < root->word) { insert(root->left, item); } if (item > root->word) { insert(root->right, item); } }I am writing a program for a project at school that requires us to create a Binary Search Tree based on data read from a file (in this case strings). The tree should allow for duplicates by incrementing an integer value when a duplicate string is entered.
The TreeNode is a struct as follows:
struct TreeNode { string word; int count; TreeNode * left; TreeNode * right; };The problem I am having is when I try to call the insert function the program crashes. I run the debugger and I get the following error:
Exception thrown at 0x00E2A87C in Proj12.2.exe: 0xC0000005: Access violation reading location 0x00000014.
What is causing this error? Here is the rest of the relevant code:
TreeNode * Root = new TreeNode; Root->right = NULL; void insert(TreeNode *& root, string item) { //insert function, called by Root->right,temp if (root->word == item) { root->count++; return; } if (root == NULL && root->word != item) { root = new TreeNode; root->left = NULL; root->right = NULL; root->word = item; root->count = 1; return; } if (item < root->word) { insert(root->left, item); } if (item > root->word) { insert(root->right, item); } }最满意答案
if(root == NULL)应该是您在尝试使用 - >运算符访问任何数据成员之前执行的第一次检查。 condition:if(root-> word == item)condition:if(root == NULL && root-> word!= item)
您的root为NULL,然后您尝试访问导致崩溃的root-> word。 您正尝试使用无效指针访问数据成员。
if(root == NULL) should be the first check you perform before trying to access any data members using the -> operator. condition: if(root->word == item) condition: if (root == NULL && root->word != item)
Your root is NULL and then you are trying to access root->word which is causing the crash. You are trying to access data member using an invalid pointer.
更多推荐
发布评论