为什么 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++ 中添加两个指针.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!