C++ 指针相加相减

如果两个指针向同一个数组,它们就可以相减,其结果可以分两个方面理解
1、对于内存块操作时,是两个指针之间的元素数目,例如:

#include <malloc.h>
#include <iostream>
using namespace std;
int main()
{
    int *first = (int*)malloc(20 * sizeof(int));
    int *last = first + 20;
    int addr_diff = last - first;


    cout << "first addr :" << first << endl;
    cout << "last addr :" << last << endl;
    cout << "same last addr :" << first + 20 << endl;
    cout << "same first addr :" << last - 20 << endl;
    cout << "addr_diff = " << addr_diff << endl;


    cout << "first addr :" << first << endl;
    cout << "first addr + 1 :" << first + 1<< endl;


    if (first != NULL)
    {
        free(first);
        first = NULL;
    }
    
    system("pause");
    return 0;
}

这里,申请了一个20(int)大小的内存块first,我们加上20得到内存块结束地址last。再对其做一系列加减后得

结果:

first addr :00424840
last addr :00424890
same last addr :00424890
same first addr :00424840
addr_diff = 20
first addr :00424840
first addr + 1 :00424844

看来这里的地址加减是以申请的指针类型为单位加减的。

2、对于数组而言,先直接看个例子:

#include <stdio.h>
#include <stddef.h>
#include <iostream>
struct stuff{
    char name[16];
};

struct stuff array[]={
    {"The"},
    {"quick"},
    {"brown"},
    {"fox"},
    {"jumped"},
    {"over"},
    {"the"},
    {"lazy"},
    {"dog."},
    {""}
};

int main()
{
    struct stuff   *p0= & array[0];
    struct stuff   *p8= & array[8]; 
    ptrdiff_t      diff=p8-p0; 
    ptrdiff_t      addr_diff=(char*)p8-(char*)p0;

    printf("&array[0]=p0=%d\n",(void*)p0);
    printf("&array[8]=p8=%d\n",(void*)p8);

    printf("The difference of pointers is %ld\n",(long)diff); 
    printf("The difference of addresses is %ld\n",(long)addr_diff);
    printf("p8-8=%d\n",(void*)(p8-8));

    printf("p0+8=%d(same as p8)\n",(void*)(p0+8));

    system("pause");
    return 0;
}      

这个例子是网上找的,由于有点问题修改了下。
运行结果为:

&array[0]=p0=10326064
&array[8]=p8=10326192
The difference of pointers is 8
The difference of addresses is 128
p8-8=10326064
p0+8=10326192(same as p8)

据上例可以发现,指针相加减 必须同属于一个内存块内,或是数组中,如果是连个不同内存块或者数组的话,相加减

就不会有正确的结果的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

画中小林

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值