【发布时间】:2021-11-07 10:00:09
【问题描述】:
程序应打印字符串数组的每个字符。
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char* numbers[10]{"One", "Too", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Zero"};
/* This version did not work. Why?
for (const char** ptr = numbers; *ptr != nullptr; *ptr++) {
const char* pos = *ptr;
while (*pos != '\0')
cout << *(pos++) << " ";
}
*/
for(unsigned int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); ++i)
{
const char* pos = numbers[i];
while(*pos != '\0')
printf("%c ", *(pos++));
printf("\n");
}
return 0;
}
我知道我的代码是 C++17 和 C 的混合体(在从 C 到 C++ 的转换中,nullptr、cout 是两个示例),但不确定第一个 for-loop 与
for (const char** ptr = numbers; *ptr != nullptr; *ptr++)
是否正确。它出什么问题了? 是否有“最佳实践”来循环遍历字符串数组(char 数组,还不是字符串对象),尤其是在这种情况下,我想捕获双指针?谢谢!
【问题讨论】:
-
考虑将minimal reproducible example 放在一起,它实际上可以编译。
-
谢谢!你真的很快!帖子已使用完整代码进行了编辑。
-
数组有长度,它们不会以任何标记结束,例如 NULL 或类似的。自己添加适当的结束标记。
-
“双指针”这个词是模棱两可的,最准确的指类型
double*。我建议改用“指向指针的指针”一词(正如pointer-to-pointer 标签描述所建议的那样)。 -
我也在其他地方读过关于“指针到指针”的 cmets。我会尽量按照建议使用。
标签: c++ arrays char pointer-to-pointer