c++ - 在 C++ 中用双指针打印字符串数组的每个字符
问题描述
该程序应打印字符串数组的每个字符。
#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 数组,还不是字符串对象),尤其是在这种情况下,我想捕获双指针?谢谢!
解决方案
两件事情 -
首先,在这个循环表达式中,你不需要ptr
在增加它之后取消引用 - *ptr++
。
for (const char** ptr = numbers; *ptr != nullptr; *ptr++)
^^
*ptr++
将被分组为 - *(ptr++)
,这意味着,(post)incrementptr
和取消引用 (post)increment 的结果。它应该是 just ptr++
,因为我们需要在执行循环体后ptr
指针指向数组中的下一个元素。numbers
其次,如果您的循环条件正在检查,nullptr
那么循环正在迭代的数组应该nullptr
作为标记来指示数组的结尾,并且您还需要增加数组的大小以调整结束标记:
const char* numbers[11] {"One", "Too", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Zero", nullptr};
通过上述更改,以下循环应打印numbers
数组字符串:
for (const char** ptr = numbers; *ptr != nullptr; ptr++) {
const char* pos = *ptr;
while (*pos != '\0')
cout << *(pos++) << " ";
cout << "\n";
}
因为,您已经在数组中添加了一个新元素numbers
来标记数组的结尾,所以要小心,在第二个循环中,您正在做sizeof(numbers)/sizeof(numbers[0])
的是获取数组大小并且它将给出11
并且第二个循环将最终访问nullptr
这将是未定义的行为. 1
从结果中减去sizeof
循环条件或pos != nullptr
在处理之前添加检查。
推荐阅读
- angular - Hasura - 身份验证操作(登录、注销、注册)
- flutter - Flutter macOS Desktop 项目发布神器位置
- kivy - 在 Kivy 中制作与小部件边界框大小完全相同的图像
- python - 树莓派,1 个 LED,带 2 个按钮
- tensorflow2.0 - TensorFlow 图像太小而无法正确显示结果
- javascript - 在我的打字代码开始之前需要一个时间延迟,在第二次迭代之前需要一个时间延迟
- android - onRangeStart() 在阅读段落时停止获取回调(遇到标点符号后)
- cors - Access-Control-Allow-Methods 没有停止 POST 调用
- python - 无法通过 API 响应排序
- python - 用于返回 jitclass 的函数的 Numba jit() 函数签名