不支持在 c 或 c++ 中添加两个指针.为什么? [英] Addition of two pointers in c or c++ not supported. why?

查看:28
本文介绍了不支持在 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++ 中添加两个指针.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆