如何使用指针反转字符串

时间:2015-03-02 03:46:13

标签: c++

我有一个带有字符串的函数,并使用前后指针将其反转。现在这是下面写的程序。我不明白的是while循环。当它指定*front = *rear , and *rear = temp //which is *front.时,我们如何仍然分别增加和减少前后。但我们切换它们不是吗?现在不是前面后面和前面的前面?还是因为它的指针?有人可以向我解释这个吗?

程序:

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

void reverse(char* s);
int main()
{
    char aString[] = "babylonia";

    cout << " please enter the string " << endl;

    reverse(aString);

    cout << aString << endl;


}

void reverse(char* s)
{
    char *front, *rear, temp;
    front = s;
    rear = s+strlen(s) - 1;
    while( front < rear)
    {
        temp = *front;
        *front = *rear;
        *rear = temp;
        front++;
        rear--;
    }

}

1 个答案:

答案 0 :(得分:1)

front = s //与front = &s[0]相同,指向数组中第一个字符的地址。
rear,它指向数组中最后一个字符的地址。

(These are just example addresses)
|0x23fde8 | 0x23fdf0| 0x23fdf8| 0x23fe00| 0x23fe08| 0x23fe10| 0x23fe18| 0x23fe20| 0x23fe28|
.---------.---------.---------.---------.---------.---------.---------.---------.---------.
|    B    |    A    |    B    |    Y    |    L    |    O    |    N    |    I    |    A    |
'---------'---------'---------'---------'---------'---------'---------'---------'---------'
     ^                                                                               ^

首先,front指向一个地址,例如0x23fde8rear指向0x23fe28
现在,当您用星号取消引用它时可以访问内存的那一部分,你可以想象一个如上图所示的容器,或者你可以想象你用星号*打开容器

当您通过front++++front递增前面时,它会递增到下一个内存地址位置。在rear----rear递减到下一个地址位置的同时。 它不会更改地址,但是当您取消引用它时,您可以访问该内容。

下面你看到第一个 last 已被交换,但地址保持不变

|0x23fde8 | 0x23fdf0| 0x23fdf8| 0x23fe00| 0x23fe08| 0x23fe10| 0x23fe18| 0x23fe20| 0x23fe28|
.---------.---------.---------.---------.---------.---------.---------.---------.---------.
|    A    |    A    |    B    |    Y    |    L    |    O    |    N    |    I    |    B    |
'---------'---------'---------'---------'---------'---------'---------'---------'---------'
               ^                                                           ^
             front                                                        rear

我希望这有助于您了解*frontfront

之间的区别