gpt4 book ai didi

c++ - 在 C++03 中,如何在没有重复代码的情况下在堆栈上创建非常量 C 字符串数组?

转载 作者:搜寻专家 更新时间:2023-10-31 02:10:40 25 4
gpt4 key购买 nike

我正在为一个模块编写单元测试,该模块在 C++03 中采用 getopt 的可变 C 字符串数组。 .函数参数是 char*const[]。我想在函数内部的堆栈上创建参数。我目前的解决方案是:

char args_stor[][1024] = {
"parser",
"-o",
"SomeValue"
};
char* args[] = {
args_stor[0],
args_stor[1],
args_stor[2]
};

如何避免重复的部分,如果可能,将其转化为一条语句?

函数声明为:

int getopt(int argc, char* const argv[], const char *optstring);

因此用例是:

getopt(3, args, ":o:");

最佳答案

我认为你做不到。 getopt 需要 char * const[]。您可以做的唯一改进是为每个参数使用单独的 char[] 声明而不是二维数组。这样您就可以只分配所需的空间:

char opt1[] = "parser";
char opt2[] = "-o";
char *args[] = { opt1, opt2 };

关于c++ - 在 C++03 中,如何在没有重复代码的情况下在堆栈上创建非常量 C 字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44908185/

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