問題描述
為什么 c 或 c++ 不支持添加兩個指針.
Why addition of two pointers not supported in c or c++.
當(dāng)我這樣做時,
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);
}
我很確定你總能想出一個偏移計算,讓你用加法來實現(xiàn)你想要實現(xiàn)的目標(biāo).
I am quite sure that you can always come up with an offset-computation which lets do what you want to achieve with addition.
這篇關(guān)于不支持在 c 或 c++ 中添加兩個指針.為什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!