c++ - 试图理解一些通过 char 数组向后迭代的 C++ 代码
问题描述
我正在学习 C++ 教程,我正在尝试遍历每一行,但我很难过。到目前为止,我有一个 char 数组,我正在尝试使用指针和 while 循环向后迭代。我在评论中添加了尝试并了解每一位在做什么。有人可以确认我的理解吗?
#include <iostream>
using namespace std;
int main()
{
char text[] = "hello";
int nChars = sizeof(text) - 1; // finds the size of the array (equals 6), and subtracts 1. "Hello" has 5 letters, but there's an added 6th element called the stop element.
cout << nChars << endl;
char* pStart = text; // pStart will Point to first value in array.
char* pEnd = text + nChars - 1; // takes the first element in the array, adds the amount of additional elements, and subtracts 1 from the end.
while (pStart < pEnd)
{
char save = *pStart; // Save the first element (h) in "hello".
*pStart = *pEnd; // Takes the beginning element (h), adds the remaining elements, removes the termination character (nChars - 1) then sets the end as the beginning
pStart++; // Increment through the char array with the end as the beginning, working through 'o', increment to 'l', then 'l', then 'e', then 'h'.
pEnd--; //
}
return 0;
}
解决方案
推荐阅读
- php - 提交后php中的表单未重定向到页面
- python - 使用 Flask 和 PyTest 测试 SqlAlchemy 会话事件
- r - 获取错误(as.character(FUN),模式=“功能”,环境=环境):模式'功能'的对象'guide_legend'
- javascript - 使用 useEffect 跟踪一个 prop,它依赖于多个 prop
- kubernetes - Kubernetes - 匹配标签、选择器的范围
- reactjs - 我得到一个错误解决方法 - 未捕获的 TypeError:_postSchema.Post 不是构造函数
- javascript - 当另一个功能时无法停止该功能
- ruby - RSpec:与 fastlane 一起使用时从错误的模块调用“expect with”函数
- rpa - Uipath(RPA):交换excel中的两列
- javascript - 如何在 VS Code 编辑器中使用 ESLint + Airbnb 规则 + TypeScript + Stylelint 为 SCSS 配置 Vue CLI 4,并在保存时自动修复?