Addition of two pointers in c or c++ not supported. why?(不支持在 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++ 中添加两个指针.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:不支持在 c 或 c++ 中添加两个指针.为什么?


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01