c++ String copying error to struct pointer data fields -
i'm writing program uses binary search tree store names , phone numbers (phonebook basically). i've done before avl tree, , works fine. have decided switch methods implementation , not copy/paste logic , format of last one. in doing i've run weird error , have no idea why it's happening. @ first thought problem in way returned struct pointer, in string copying.
i've written basic program shows copy function returns structure, used recursively fill bst data (which read in file).
here shortened example:
#include <iostream> #include <string> using namespace std; struct node { std::string first; std::string last; std::string phone; }; node* copyfunc(std::string first, std::string last, std::string phone) { node* temp = null; temp->first = first; temp->last = last; temp->phone = phone; return temp; } int main() { std::string first, last, phone; first = "jenny"; last = "something"; phone = "8675309"; node* newstruct = null; newstruct = copyfunc(first, last, phone); cout << newstruct->first << endl; cout << newstruct->last << endl; cout << newstruct->phone << endl; cout << "never seen again..." << endl; return 0; }
now, i've tried using vs2013 debugger find out issue is, , happens on first copy: "temp->first = first;". breaks access violation warning , opens xstrings (header?) , points section: (line 2245)
if (this->_myres < _newsize) _copy(_newsize, this->_mysize); // reallocate grow"
i'm guessing, can gather seems me it's failing in creating new string fit old strings length.
the program (both example , real one) compile, hang @ point of reaching copy function.
all input appreciated, thanks!
edit: reason use pointers structures due way algorithms i'm using written. functions link nodes in bst accept node* type rather node object. ex: recursiveinsert(node* root, node* newnodetoadd);
you not initializing temp
useful before attempt use it.
node* temp = null; temp->first = first; // oops! temp null!
it easier drop pointers entirely:
node copyfunc(std::string first, std::string last, std::string phone) { node temp = {first, last, phone}; return temp; }
you should consider passing parameters const
reference instead of value. or drop function , initialize node
needed:
node newstruct = {first, last, phone}; cout << newstruct.first << endl;
Comments
Post a Comment