C++指针练习

C++ pointers exercise

本文关键字:练习 指针 C++      更新时间:2023-10-16

我在网络上找到了以下关于C++指针的完整练习,但我仍然无法理解它是如何工作的。

#include <iostream>
#include <cstring>
using namespace std;
void reverse(char *s, int n) {
    char *first = &s[0];
    char *last = &s[n-1];
    int k = 0;
    while(first < last){
        char temp = *first;
        *first++ = *last;
        *last-- = temp;
        k++;
    }
}

int main() {
    int n;
    char str[] = "Hello";
    cout << str << endl << endl;
    n = strlen(str);
    reverse(str,n);
    cout << str << endl;
    return 0;
}

我真的无法理解的部分是

*first++ = *last;
*last-- = temp;

指针基本上是内存中的地址,对于这种特定情况,它们指向内存中可以找到字符的地址。 *first是位于地址处的值(即:字符),++--递增或递减指针,从而遍历内存以指向下一个/上一个字符。

*first++ = *last;的评估结果为:

  1. 输入first指向的内存地址/位置的值,该值位于last指向的内存位置
  2. 递增first ,以便它指向下一个地址。

这相当于:

*first = *last;
first ++;

*last-- = temp;评估为:

  1. 输入内存地址/位置,last指向temp的值
  2. 递减last ,以便它指向上一个地址

我留给你一个练习,找出这两个操作是等价的:)

*first = *last; // copy data from last to first
++first; // point to the next item
*last = temp; // copy data from temp to last
--last; // point to the previous item