I have a class with parse(int argc, char* argv[]) function which I have to use to set a desired state of an object. I’m taking the parameters from the gui using stringstream and then I’m trying to convert them to char** to pass them to the function. Here’s what I’ve got:
std::stringstream sstream;
sstream << "-clip" << " " << min_x_entry.get_text()
<< " " << max_x_entry.get_text(); // etc.
std::cout << sstream.str(); // All looks good here
std::vector<std::string> args;
std::vector<char*> argv;
std::string arg;
while (sstream >> arg)
{
args.push_back(arg);
argv.push_back(const_cast<char*>(args.back().c_str()));
}
argv.push_back(0);
int argc = args.size();
for (int i = 0; i < argc; ++i)
std::cout << &argv[0][i]; // This outputs garbage
my_object.parse(argc, &argv[0]) // And this fails
What am I missing? Is there a better way of achieving this?
A problem would be reallocation of the
argsvector aspush_back()will grow the size of the vector if required:The
argvvector is storing pointers to the internals of elements inargs, so these would be invalidated.A solution would be to create the
argsvector first then create theargvvector afterwards:The
forloop that prints out theargvstrings is incorrect. This:is a
char*but starts fromith element of the first entry inargv. For example, if the first c-string inargvwas"string":change to: