我在网上找到了以下关于 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;
计算为:
- 将
first
指向的内存地址/位置放入last
指向的内存位置的值 - 自增
first
,使其指向下一个地址。
这相当于:
*first = *last;
first ++;
*last-- = temp;
计算为:
- 放入
last
指向temp
值的内存地址/位置 - 递减
last
,使其指向上一个地址
我留给你做一个练习,找出哪两个操作是等价的:)
关于C++指针练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22761766/