如何将字符串数组转换为Char*数组c++

3

我想要向下面这个函数传递参数:

execve(char *filename, char *argv[], char *envp[])

目前我的argv[]是一个字符串数组。我想将它转换为char* 数组,以便我可以将它传递给这个函数。

我查找了许多方法来将一个字符串转换为char数组,但如何将一个字符串数组转换为字符数组数组我想应该是正确的术语。有什么帮助吗?


2
你所说的字符串数组,是指类似于 string myargs[5]; 这样的形式,并且你想将其传递给 execve 函数吗? - us2012
char *argv[] 实际上是一个 char* 元素的数组。数组中的每个元素都指向一个 char* 字符串。因此,argv[0] 是一个 char* 字符串,可以被打印或使用。 - enhzflep
@us2012 是的,通过字符串数组,我是指一个由字符串组成的数组,例如 string myargs[5]。 - Hassan Jalil
2个回答

5

您需要获取 std::string 内部数据的地址。请注意,这些字符串不需要以空字符结尾,因此您需要确保所有字符串以空字符结尾。另外,作为参数传递的数组 argv 也需要将最后一个元素设置为 null 指针。您可以使用类似以下代码的方式:

std::string array[] = { "s1", "s2" };
std::vector<char*> vec;
std::transform(std::begin(array), std::end(array),
               std::back_inserter(vec),
               [](std::string& s){ s.push_back(0); return &s[0]; });
vec.push_back(nullptr);
char** carray = vec.data();

在使用C++03编译时,有一些必要的更改:

  1. Instead of using the lambda expression, you need to create a suitable function or function object doing the same transformation.
  2. Instead of using nullptr you need to use 0.
  3. In C++03 std::string is not guaranteed to be contiguous, i.e., you need an additional, auxiliary std::vector<char> to hold a contiguous sequence of characters.
  4. There are no functions begin() and end() deducing the size of an array but they can easily be implemented in C++03:

    template <typename T, int Size> T* begin(T (&array)[Size]) { return array; }
    template <typename T, int Size> T* end(T (&array)[Size]) { return array + Size; }
    
  5. The C++03 std::vector<T> doesn't have a data() member, i.e., you also need to take the address of the first element.


我需要包含任何库吗? 这些是我得到的错误: “transform”不是“std”的成员 “begin”不是“std”的成员 错误:‘end’不是‘std’的成员 警告:lambda表达式仅在-std=c++0x或-std=gnu++0x下可用[默认启用] ‘nullptr’在此作用域中未声明 - Hassan Jalil
你需要使用C++11选项进行编译,或者使用函数对象代替lambda表达式,并且使用0代替nullptr。当然,你还需要包含相关的标准头文件(在这种情况下是<algorithm><iterator><string><vector>)。 - Dietmar Kühl
在C++03中,std::string不能保证是连续的。你能引用一下标准吗? - dragonroot
@dragonroot:标准并没有说它是有保证的。然而,它并没有保证它是连续的,即没有简单引用。要求在C++11的21.4.1 [string.require]第5段中,C++03中没有相应的要求。 - Dietmar Kühl
@DietmarKühl,使用return s.c_str()代替s.push_back(0); return &s[0];是否足够? - anatolyg
显示剩余10条评论

0

以下方法对我有效:

const char *argv[]{"-l", nullptr};
execvp("ls", const_cast<char**>(argv));

由于它们是字符串文字,您不需要以 null 结尾,但仍需要在数组末尾添加 null 字符串。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接