我在这里理解const的用法有困难:
char* const args[];
Run Code Online (Sandbox Code Playgroud)
这是否意味着args不能指向新地址?它与以下内容有何不同:
const char* args[];
Run Code Online (Sandbox Code Playgroud)
此外,我正在尝试遍历此列表并使用单个for循环语句将值附加到字符串:
string t_command;
for(char** t= args; (*t) != NULL ; t++ && t_command.append(*t + " ")) {}
Run Code Online (Sandbox Code Playgroud)
我没有在这里做点什么,我无法弄清楚是什么.
Jos*_*eld 11
char* const args[];
Run Code Online (Sandbox Code Playgroud)
args是一个数组.数组中的每个元素都是指向的char.那些指针是const.您无法修改数组的元素以指向其他位置.但是,您可以修改char他们指向的s.
const char* args[];
Run Code Online (Sandbox Code Playgroud)
args仍然是一个数组.数组中的每个元素仍然是指针char.但是,指针不是 const.您可以修改数组的元素以指向其他位置.但是,您无法修改char他们指向的内容.
图表时间:
Args:
?????????????????????????
? ? ? ? ? ? ? // In the first version, these pointers are const
?????????????????????????
? ??? ??? ??? ??? ???
? ?
????? ?????
? c ? ? c ? // In the second version, these characters are const
????? ?????
Run Code Online (Sandbox Code Playgroud)
通常,当你有一个指向字符的指针时,这些字符本身就是数组的一部分(一个C风格的字符串),在这种情况下,它看起来像这样:
Args:
?????????????????????????
? ? ? ? ? ? ? // In the first version, these pointers are const
?????????????????????????
? ????????? ??? ???
? ?
?????????? ??????????
? c ? c ? ? c ? c ? // In the second version, these characters are const
?????????? ??????????
Run Code Online (Sandbox Code Playgroud)
至于遍历数组,您尝试将args数组视为以null结尾.这不是大多数数组的工作方式.您应该使用索引迭代到数组中.
另请注意,您无法将数组和字符串文字一起添加(如*t ++ " ").将一侧转换为a std::string使其更容易.
所以,如果N是大小args:
for (size_t i = 0; i < N; i++) {
t_command.append(std::string(args[i]) + " "))
}
Run Code Online (Sandbox Code Playgroud)