gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:58:45 24 4
gpt4 key购买 nike

我正在为我的操作系统课做作业。我们可以选择使用 C 或 C++,所以我决定使用 C++,因为我在工作中使用 C++ 的时间比 C 晚一些。

我需要调用(从“$ man execvp "在 Linux 上)

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

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

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com