I'm having trouble inserting char* into a vector< char*>
When I do the 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 I 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(); it < redn.end(); it++)
cout << *it << endl;
I got an output of:
just pushed back: Hello
just pushed back: b
just pushed back: World
just pushed back: d
p0s
World
d
It seems to me that *it is pointing to the wrong thing.. Would anybody tell me what's going on and how I could fix this?
What is wrong in your code?
Other answers explain you how to do it in a better way. My answer explains why your code doesn't work as you expected it to and a quick fix to get it working.
With the statement:
delete[] cstr;
You delete the string after you push the object in to the vector, this causes your vector elements to point to something that has already been de-allocated.
comment out that line and check again, it will work.
Here is the working sample of your code on Ideone.
Your vector in this case needs to take the ownership of deleting each of the contained object pointer which points to a dynamically allocated memory space.
See this for how to do that.