微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

指针减去数组和变量中的指针

如何解决指针减去数组和变量中的指针

谁能帮我解决这个问题。 我认为指针是一个保存变量地址的对象。所以当我减去一个指向指针的指针时。得到这个结果。

int a = 2;
int b = 7;
int* c = &a;
int* d = &b;
int e = c - d; // = 3


int array[] = { 1,2,6,4,7,8,5,3 };
int* f = &array[0];
int* g = &array[8];
int h = g - f; // = 8 

解决方法

在你的第一个例子中,减去独立的指针是没有意义的。考虑你的例子:

int a = 2;
int b = 7;
int* c = &a;
int* d = &b;
int e = c - d; // Nonsense

如果您要尝试使用指针执行“2 - 7”操作,那么您首先必须取消对指针的引用(评估指针指向的变量所保存的值):

int e = (*c) - (*d);
,

你是对的,一个指针保存了内存中对象的地址。在 C 和 C++ 中,我们可以进行指针运算,让我们彼此减去指针以及更多。减去指针为我们提供了内存中两个地址之间的距离。距离的单位由指针类型决定。这意味着减去两个 int* 将得出您的地址相距多少 int。在您的情况下,变量 e 将是 a 存储在内存中的位置与 b 存储在内存中的位置之间的距离。运行你的代码,我得到了 e=1。我期望这是因为 ab 是在彼此之后定义的,因此预计它们将占据堆栈上的两个相邻空间,但我猜这是编译器决定的。 对于数组 另一方面,根据定义,所有元素都一个接一个地存储,因此任何数组的第一个和第八个元素之间的距离始终为 8。也看看下面的代码:

int a = 2;
int b = 7;
int* c = &a;
int* d = &b;
int e = d - c; // e=1
//the unit of measurement for pointer subtraction is the type of the pointer
//therefore although first byte of b is stored 4 bytes (sizeof(int)) after the
//first byte of a,we get '1' as the distance. but we cast the pointer to another type
//say char,we get distance based on that type
int f= (char*)d-(char*)c;//f=4 or e*4 since sizeof(int)=4*sizeof(char) (on this particular environment)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。