我正在为我的操作系统课程分配作业。我们可以选择使用C或C ++,因此我决定使用C ++,因为我在工作上比C练习了一段时间。
我将需要调用(从Linux上的“ $ man execvp ”)
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 ++中那样将参数放入,则需要进行少量转换才能获得所需的char ** execvp
。幸运的是,两者std::vector
和std::string
在内存中都是连续的。但是,astd::vector<std::string>
不是指针数组,因此您需要创建一个指针。但是您也可以使用a 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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句