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++ 中添加两个指针.为什么?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
