我在网上找到了以下关于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;发布于 2014-03-31 12:45:04
指针基本上是内存中的地址,在这种特殊情况下,指针指向内存中的地址,您可以在其中找到字符。*first是在地址处的值(即:字符),使用++和--,您可以增加或减少指针,从而遍历内存,指向下一个/前一个字符。
*first++ = *last;被评价为:
first指向的内存地址/位置,该值位于last点所在的内存位置first,以便它指向下一个地址。这相当于:
*first = *last;
first ++;*last-- = temp;被评价为:
last指向temp值的内存地址/位置last,使其指向前一个地址我留给你们一个练习,看看哪两个操作是等价的:)
发布于 2014-03-31 12:45:09
*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 itemhttps://stackoverflow.com/questions/22761766
复制相似问题