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

Addition of two pointers in c or c++ not supported. why?(不支持在 c 或 c++ 中添加两个指针.为什么?)
本文介绍了不支持在 c 或 c++ 中添加两个指针.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

为什么 c 或 c++ 不支持添加两个指针.

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

当我这样做时,

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

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

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

int diff = ptr - ptr1;

推荐答案

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

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.

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

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
", *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.

这篇关于不支持在 c 或 c++ 中添加两个指针.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)