c++stringvector

How to pass a vector of strings to execv


I have found that the easiest way to build my program argument list is as a vector of strings. However, execv expects an array of chars for the second argument. What's the easiest way to get it to accept of vector of strings?


Solution

  • execv() accepts only an array of string pointers. There is no way to get it to accept anything else. It is a standard interface, callable from every hosted language, not just C++.

    I have tested compiling this:

    std::vector<string> vector;
    const char *programname = "abc";
    
    const char **argv = new const char* [vector.size()+2];   // extra room for program name and sentinel
    argv [0] = programname;         // by convention, argv[0] is program name
    for (int j = 0;  j < vector.size()+1;  ++j)     // copy args
            argv [j+1] = vector[j] .c_str();
    
    argv [vector.size()+1] = NULL;  // end of arguments sentinel is NULL
    
    execv (programname, (char **)argv);