首页 > 解决方案 > 试图理解一些通过 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;
}

标签: c++

解决方案


推荐阅读