如何将向量传递给execvp

neu*_*cer 3 c++ vector execvp

我想将一个向量作为第二个参数传递给execvp.可能吗?

小智 7

是的,通过利用矢量使用的内部数组,它可以非常干净地完成.

这将起作用,因为标准保证其元素是连续存储的(参见/sf/answers/204630331/)

#include <vector>

using namespace std;

int main(void) {
  vector<char *> commandVector;

  // do a push_back for the command, then each of the arguments
  commandVector.push_back("echo");
  commandVector.push_back("testing");
  commandVector.push_back("1");
  commandVector.push_back("2");
  commandVector.push_back("3");  

  // push NULL to the end of the vector (execvp expects NULL as last element)
  commandVector.push_back(NULL);

  // pass the vector's internal array to execvp
  char **command = &commandVector[0];

  int status = execvp(command[0], command);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)