使用指针反转字符数组

Reverse char array using pointers

无法理解 while 中发生的事情 如果可能的话,请形象化。

int main() 
{

        char text[] = "hello";
        int nChars = sizeof(text)-1;

        char *pStart = text;
        char *pEnd = text + nChars - 1;

        //can't understand this part 
        while (pStart < pEnd)
        {
            char tmp = *pStart;
            *pStart = *pEnd;
            *pEnd = tmp;

            pStart++;
            pEnd--;
        }

        cout << text << endl;

        return 0;
}

这是一个简单的交换机制。在 while 循环中,您的代码正在交换值。见附图。

您的代码只是简单地交换 text 中的字符。这里发生的是:-

  1. 您创建一个大小为 6 的字符数组 text 存储 "hello[=57=]"。

  2. nChars 因为你已经分配代表文本中除 [=13=] 之外的字符数,所以这里是 5(类似于 strlen)。

  3. pStart指向文本的第一个字母(即'h'),而pEnd指向'o'(不是[=13= ]).

  4. 第一个 tmp 被赋值为 'h'。然后 pStart's 字符被替换为 pEnd 的字符,即 'o'。然后 pEnd's 字符被分配给存储在 tmp 中的字符。因此 pStartpEnd 中的字符被交换(但指针仍然指向相同的位置,这里要小心!)。

  5. pStart 递增 & pEnd 递减(位置明智而不是字符明智,在这里再次小心!!)。所以现在 pStart 指向 'e' & pEnd 指向 'l'.

  6. 程序重复!!!