C++指针练习
C++ pointers exercise
我在网络上找到了以下关于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
,以便它指向上一个地址
我留给你一个练习,找出这两个操作是等价的:)
*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
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 加速C++练习2.4
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- C++ 独特指针练习的向量
- 练习中出现空指针错误
- 练习程序在尝试学习指针时崩溃
- 指针练习改进
- C++ 危险指针练习
- 跳到C++第13章练习问题4-指针
- 很好的资源,练习c++数组和指针
- 练习:C++中的指针和引用
- C++指针练习
- 需要帮助理解指针练习的输出