when you push_back heap-allocated char into a vector in c++ -
i'm having trouble inserting char* vector< char*>
when following:
string str = "hello b world d" char *cstr, *p; vector<char*> redn; cstr = new char [ (str.size)+1 ]; strcpy(cstr, str.c_str()); //here tokenize "hello b world d" p = strtok(cstr," "); while(p!=null){ redn.push_back(p); cout << "just pushed back: " << redn.back() << endl; p = strtok(null," "); } delete[] cstr; //now check for(it= redn.begin(); < redn.end(); it++) cout << *it << endl;
i got output of:
just pushed back: hello pushed back: b pushed back: world pushed back: d p0s world d
it seems me *it pointing wrong thing.. tell me what's going on , how fix this?
what wrong in code?
other answers explain how in better way. answer explains why code doesn't work expected , quick fix working.
with statement:
delete[] cstr;
you delete string after push object in vector, causes vector elements point has been de-allocated.
comment out line , check again, work.
here working sample of code on ideone.
your vector in case needs take ownership of deleting each of contained object pointer points dynamically allocated memory space.
see this how that.
Comments
Post a Comment