algorithm - Visual Studio C++ error reading location -
i'm having guess simple problem. i'm practicing in coding binary tree(first time, maybe in year, i've looked again @ c++). so, when launch code in vs 2013, error "unhandled exception .... reading location address
". , when try debugging it, after creating root tree , trying add first leaf, happens, right , left leaves have addresses, don't have values(they pointed unable read memory).
but, when load code online compiler, works perfectly. maybe it's settings in vs, because don't have other variants, why works in online compiler , doesn't work in vs.
here code:
#include <iostream> #include <string> using namespace std; struct node { string value; int key; node* left; node* right; }; void addnodetotree(node* tree, int key, string value) { if (key < tree->key) { if (tree->left != nullptr) { addnodetotree(tree->left, key, value); } else { node* node = new node(); node->key = key; node->value = value; cout << "key " << key << " leaf has been added left" << endl; tree->left = node; } } else if (key > tree->key) { if (tree->right != nullptr) { addnodetotree(tree->right, key, value); } else { node* node = new node(); node->key = key; node->value = value; cout << "key " << key << " leaf has been added right" << endl; tree->right = node; } } else { cout << "key " << key << " exists." << endl; } } void printtree(node* node) { if (node != null) { if (node->left != null) { printtree(node->left); } cout << node->key << " "; if (node->right != null) { printtree(node->right); } } else { cout << "the tree empty"; } } int main() { node* tree = new node(); tree->key = 50; tree->value = 2591; addnodetotree(tree, 20, "124525"); addnodetotree(tree, 80, "124525"); addnodetotree(tree, 10, "124525"); addnodetotree(tree, 30, "124525"); addnodetotree(tree, 50, "124525"); printtree(tree); delete tree; return 0; }
it not vs error - when allocate node
structure left
, right
member fields uninitialized, checks against nullptr
further on fail though left
/right
nodes empty , operate on invalid nodes.
solution 1:
use class instead of struct , initialize fields in constructor:
class node { public: node() : left(nullptr), right(nullptr), key(0) { } string value; int key; node* left; node* right; };
solution 2:
use function creates , initializes new node:
struct node { string value; int key; node* left; node* right; }; node* createnode(int key = 0) { node* node = new node(); node->left = nullptr; node->right = nullptr; node->key = key; return node; }
or suggested in comments add constructor struct:
struct node { node() : left(nullptr), right(nullptr), key(0) { } string value; int key; node* left; node* right; };
solution 3:
if c++11 available, use data member initializers (but not supported in vs far know):
struct node { string value; int key = 0; node* left = nullptr; node* right = nullptr; };
Comments
Post a Comment