如果两个指针向同一个数组,它们就可以相减,其结果可以分两个方面理解
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)
就不会有正确的结果的。