如何将字符串向量传递给 execv
我发现构建我的程序参数列表的最简单方法是作为字符串向量.但是, 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?
推荐答案
execv()
只接受字符串指针数组.没有办法让它接受其他任何东西.它是一个标准接口,可从所有托管语言调用,而不仅仅是 C++.
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++.
我已经测试编译这个:
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);
相关文章