指针算数运算

指针移动

一次移动1个单位p++,p--

#include <iostream>
using namespace std;

int main(int argc, char const *argv[])
{
    int a = 4;
    int *p;
    p = &a;
    cout << "p++之前p的地址:"<<p<<endl;
    p++;
    cout << "p++之后p的地址:"<<p<<endl;
    p--; //指针归位 等价于p = &a;
    cout << "p--之后p的地址:"<<p<<endl;
    return 0;
}
p++之前p的地址:0x7ffeef30ecac
p++之后p的地址:0x7ffeef30ecb0
p--之后p的地址:0x7ffeef30ecac

十六进制:0123456789abcdef

多想想底层是怎么分配的,给定p的地址,立马心算出p++,p--的地址

指针移动n个单位

int n =4;
int *p = &n;
//指针移动1个单位后的地址
cout << p+1 << endl;
//指针移动x个单位后的地址
cout << p+x << endl;
//指针移动x*sizeof(int)后的地址
cout << p+x*sizeof(int) << endl;

指针的加减并非数字是那个的加减,而是移动了多少个数据结构

来看看下面的测试:

#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
    int a =4;
    int n =10;
    int *p = &a;
    cout<<"p:"<< p << endl;
    p++;
    cout<<"p:"<< p << endl;
    cout<<"p+4:"<< p+4 << endl;
    cout<<"p:"<< p << endl;
    p++;
    cout<<"p:"<< p << endl;
    cout<<"sizeof(int):"<<sizeof(int) << endl;
    // int *final_p = p+n*sizeof(int);
    int *final_p = p+n*sizeof(int);
    cout<<"p+n*sizeof(int): "<<final_p<<endl;
    p+=n;
    cout<<"p移动n=10个单位之后:"<<p<<endl;

    cout<<final_p-p<<endl;
    p = &a;
    return 0;
}
p:0x7fff56ced5cc
p:0x7fff56ced5d0
p+4:0x7fff56ced5e0
p:0x7fff56ced5d0
p:0x7fff56ced5d4
sizeof(int):4
p+n*sizeof(int): 0x7fff56ced674
p移动n=10个单位之后:0x7fff56ced5fc
30

results matching ""

    No results matching ""