c++ - 需要在 C++ 中使用 char** 而不是 std::string*

标签 c++ c arrays string char

我正在为我的操作系统类(class)做作业。我们可以选择使用 C 或 C++,所以我决定使用 C++,因为我最近在工作中练习它比 C 更晚。

我需要打电话(从“ $ man execvp "在 Linux 上)

int execvp(const char *file, char *const argv[]);

这(除非我弄错了)意味着我需要一个 C 风格的 char* 数组(C 中的字符串数组),并且无法使用 C++ 中的 std::string 。

我的问题是:在 C++ 中创建/使用 char* 数组而不是字符串数组的正确方法是什么?大多数人倾向于说 C++ 中不再使用 malloc(我现在尝试了一些复杂的方法)

char** cmdList = (char**)malloc(128 * sizeof(char*));

但我不知道如何在没有的情况下制作 char* 数组。 即使我使用 C++,仍然适合用 C 语言解决这个问题吗?我还没有遇到过无法在 C++ 中使用字符串的情况。

感谢大家的宝贵时间。

最佳答案

如果你把你的论点放入 std::vector<std::string> ,就像在 C++ 中一样,那么您需要一个小的转换来获取 execvp 的 char** 。想要。幸运的是,两者都是std::vectorstd::string在内存中是连续的。然而,std::vector<std::string>不是一个指针数组,因此您需要创建一个。但你可以只使用 vector也是为了这个。

// given:
std::vector<std::string> args = the_args();
// Create the array with enough space.
// One additional entry will be NULL to signal the end of the arguments.
std::vector<char*> argv(args.size() + 1);
// Fill the array. The const_cast is necessary because execvp's
// signature doesn't actually promise that it won't modify the args,
// but the sister function execlp does, so this should be safe.
// There's a data() function that returns a non-const char*, but that
// one isn't guaranteed to be 0-terminated.
std::transform(args.begin(), args.end(), argv.begin(),
  [](std::string& s) { return const_cast<char*>(s.c_str()); });

// You can now call the function. The last entry of argv is automatically
// NULL, as the function requires.
int error = execvp(path, argv.data());

// All memory is freed automatically in case of error. In case of
// success, your process has disappeared.

关于c++ - 需要在 C++ 中使用 char** 而不是 std::string*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34843935/

相关文章:

c - K&R 第二版中的错误?

C 字符串修改

java - 在数组上调用时,indexOf 无法解析为类型

c++ - Thrift 服务器 : detect client disconnections (C++ library)

c++ - 显示未显示在 qt 中其他类的文本框中

c++ - 制作 : c: command not found

c++ - 避免编译开销

带有前向声明的 C 结构 typedef

java - 如何解决: Array type expected,找到int?在冒泡排序中使用数组而不是列表

c# - IEnumerable<T> 与 T[]