不支持在 c 或 c++ 中添加两个指针。为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25667580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:23:08  来源:igfitidea点击:

Addition of two pointers in c or c++ not supported. why?

c++cpointers

提问by vignesh babu

Why addition of two pointers not supported in c or c++.

为什么在 c 或 c++ 中不支持添加两个指针。

When I do,

当我做,

int *ptr,*ptr1;
int sum = ptr + ptr1;

C or C++ throws an error. While it supports,

C 或 C++ 抛出错误。虽然它支持,

int diff = ptr - ptr1;

回答by midor

Pointers contain addresses. Adding two addresses makes no sense, because you have no idea what you would point to. Subtracting two addresses lets you compute the offset between these two addresses, which may be very useful in some situations.

指针包含地址。添加两个地址是没有意义的,因为你不知道你会指向什么。减去两个地址可以让您计算这两个地址之间的偏移量,这在某些情况下可能非常有用。

Edit: To address the common wish for finding the mid consider this (purely as an example):

编辑:为了解决寻找中频的共同愿望,请考虑这一点(仅作为示例):

#include <stdio.h>
int main (int argc, char **argv){
    int arr[] = {0,1,2,3,4,5,6,7,8,9};
    int *ptr_begin = arr;
    int *ptr_end = &arr[9];
    int *ptr_mid = ptr_begin + (ptr_end - ptr_begin)/2;
    printf("%d\n", *ptr_mid);
}

I am quite sure that you can always come up with an offset-computation which lets do what you want to achieve with addition.

我很确定你总是可以想出一个偏移计算,它可以让你用加法来实现你想要实现的目标。

回答by Othman Benchekroun

Adding two addresses actually can be useful, You may need to know the middle address between two adresses for example (a+b)/2 ( for the guy who want to think of pointers as house numbers, this would give him the number of the house in the middle between the two houses ), I think that adding two addresses should be allowed because you can do it anyway using casts :

添加两个地址实际上很有用,您可能需要知道两个地址之间的中间地址,例如 (a+b)/2 (对于想要将指针视为门牌号码的人,这会给他房子在两栋房子之间),我认为应该允许添加两个地址,因为无论如何您都可以使用演员表来做到这一点:

int *ptr,*ptr1;
int sum = (int)ptr + (int)ptr1;

EDIT : I'm not saying that using adding addresses is obligatory in some cases, but it can be usefull when we know how to use it.

编辑:我并不是说在某些情况下必须使用添加地址,但是当我们知道如何使用它时它会很有用。

回答by DevonHorizon

To put it plainly, difference between two pointers give the number of elements of the type that can be stored between the two pointers, but adding them doesn't quite give any meaningful functionality. If there's no meaningful functionality then doesn't it make sense that it is not supported.

说白了,两个指针之间的差异给出了可以存储在两个指针之间的类型元素的数量,但是添加它们并没有给出任何有意义的功能。如果没有有意义的功能,那么它不受支持就没有意义了。