指针的加减法运算及对“指针 = 地址 + 偏移量”的理解
本文通过c++示例代码演示指针的加减法运算及对“指针 = 地址 + 偏移量”的理解。
概述
本文通过c++示例代码演示指针的加减法运算及对“指针 = 地址 + 偏移量”的理解。
研究示例
1. 首先来检查各种变量类型所占的内存大小
#include <iostream>
using namespace std;
int main(){
cout << sizeof(char) << endl; // 1 Byte
cout << sizeof(short) << endl; // 2 Byte
cout << sizeof(int) << endl; // 4 Byte
cout << sizeof(long long) << endl; // 8 Byte
return 0;
}
2. 各类型的指针进行加减运算
各类型的指针进行加减运算是以元素为单位进行加减,而非地址的最小单位(1个Byte)。以下演示各类型指针指向的地址:
#include <iostream>
using namespace std;
int main(){
char *p_char = new char('a');
cout << "*p_char = " << *p_char << endl;
cout << "p_char = " << (void*)p_char << endl; // char指针在使用cout输出会直接打印变量而非地址,要加(void*)
cout << "p_char + 1 = " << (void*)(p_char + 1) << endl;
cout << "p_char + 2 = " << (void*)(p_char + 2) << endl;
cout << "p_char - 1 = " << (void*)(p_char - 1) << endl;
// ...(以下省略部分代码)
3. 强制转换指针类型对地址进行解析
可以强行指定指针的类型对同一块内存的数据进行不同方式的解析。例如:
#include <iostream>
using namespace std;
int main(){
char arr[10] = {0,1,2,3,4,5,6,7,8,9};
unsigned int l = sizeof(arr)/sizeof(arr[0]);
char* p_char = arr;
cout << "*p_char = " << (int)*p_char << endl;
cout << "*(p_char + 1) = " << (int) *(p_char + 1) << endl;
cout << "*(p_char + 2) = " << (int)*(p_char + 2) << endl;
cout << "*(p_char + 3) = " << (int)*(p_char + 3) << endl;
cout << "*(p_char + 9) = " << (int)*(p_char + 9) << endl;
// ...(以下省略部分代码)
总结
本文通过几个简单的c++程序验证了“指针 = 地址 + 偏移量”这一结论,希望能对指针如何操作内存有更深入的理解。
另外,本文所讨论的指针均为变量指针,而函数指针不能进行加减运算(会报warning: pointer to a function used in arithmetic),我会另写一篇文章讨论函数指针。
以上就是电脑114游戏给大家带来的关于指针的加减法运算及对“指针 = 地址 + 偏移量”的理解全部内容,更多攻略请关注电脑114游戏。
电脑114游戏-好玩游戏攻略集合版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!