简体   繁体   English

C ++指针练习

[英]C++ pointers exercise

I found the following complete exercise about C++ pointers on the web, but I can't still understand how it works. 我在网上找到了以下有关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;
}

The part that I really can't understand is 我真正无法理解的部分是

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

Pointers are basically addresses in memory, for this specific case they point to addresses in memory where you can find characters. 指针基本上是内存中的地址,对于这种特定情况,它们指向内存中可以找到字符的地址。 *first is the value (ie: the character) which is at the address and with ++ and -- you increment or decrement the pointer, thus walking through the memory to point to the next/previous character. *first是在地址上并带有++的值(即:字符),并且--您可以递增或递减指针,从而遍历内存以指向下一个/上一个字符。

*first++ = *last; is evaluated as: 评估为:

  1. Put in the memory address/location where first points the value which is at the memory location where last points first指向的存储地址/位置中输入值, last指向的存储位置
  2. increment first , so that it points to the next address. first递增,使其指向下一个地址。

This is equivalent to: 这等效于:

*first = *last;
first ++;

*last-- = temp; is evaluated as: 评估为:

  1. Put in the memory address/location where last points the value of temp 放入last指向temp值的内存地址/位置
  2. Decrement last , so that it points to the previous address last递减,使其指向先前的地址

I leave to you as an exercise to find out with which two operations is this equivalent :) 我留给您做练习,以找出这两个操作是等效的:)

*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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM