c++ - 从字符串构造 char*const*

标签 c++ c string char constants

我正在尝试将字符串转换为 const*char* 以便能够调用库函数。我的代码如下:

// myVec is simply a vector<string> 

vector<string> myVec;
/* stuff added to myVec
 * it is a vector of words that were seperated by whitespace
 * for example myVec[0]=="Hey"; myVec[1]=="Buck"; myVec[2]=="Rogers"; etc...
 */

char*const* myT = new char*[500]; //I believe my problem stems from here

for(int z=0; z<myVec.size(); z++) {
   string temp=myVec[z]+=" "; 
   myT[z]=temp.c_str();
}
//execv call here

我正在为 execv() 的第二个参数构造它.

编译器总是会抛出各种错误,当我修复一个错误时,会弹出另一个错误(从我使用的解决方案/google-fu 看来相当循环)。

最佳答案

execv 的签名要求参数数组指向可修改的 C 风格字符串。因此,与其他答案所暗示的相反,c_str() 并不是一个好主意。

虽然在 C++03 中不能保证,但事实是我所知道的 std::string 的所有实现都将数据存储在连续的 NULL 终止内存块中(这在C++11),所以你可以利用它来发挥你的优势:创建一个指向可修改字符数组的指针 vector ,使用输入 vector 中字符串的缓冲区初始化值,并将该数据 block 的地址传递给 execv:

std::vector<char*> args;
args.reserve(myVec.size()+1);
for (std::vector<std::string>::iterator it=myVec.begin(); it != myVec.end(); ++it) {
   args.push_back(&((*it)[0]);
}
args.push_back(0);   // remember the null termination:

execv("prog", &args[0]);

关于c++ - 从字符串构造 char*const*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14960969/

相关文章:

c++ - 如何在 Windows 上拦截 C++ 中的段错误?

c++ - StringPiece/StringRef 习语不受欢迎有什么原因吗?

c - 为什么 SIGUSR1 会杀死我的 dd 子进程?

java - 将动态 string[] 拆分为固定大小的数组

sql - 通过匹配词比较字符串

c++ - 谁设计/设计了 C+ +'s IOStreams, and would it still be considered well-designed by today' s 标准?

c++ - 在 C++ STL 类型的静态实例上使用 OpenMP threadprivate 指令

c - 有限状态机实现

c - 为什么 *(&identifier)=value 在 C 中有效?

php - 每 x 行分割文本文件