來源博文:size_t、ptrdiff_t
對於指向同一數組arr[5]中的兩個指標之差的驗證:
數組如下:ptr = arr;-------------------------------------------------------------------------------------------int _tmain(int argc, _TCHAR* argv[]){char arr[5] = {1,2,3,4,5};char *ptr = arr;printf("%d\n",&ptr[4]-&ptr[0]);system("PAUSE");return 0;}-------------------------------------------------------------------------------------------
運行輸出:4
更換為字元數組,測試結果一樣。
《C和指標》P110 分析如下:兩個指標相減的結果的類型為ptrdiff_t,它是一種有符號整數類型。減法運算的值為兩個指標在記憶體中的距離(以數組元素的長度為單位,而非位元組),因為減法運算的結果將除以數組元素類型的長度。所以該結果與數組中儲存的元素的類型無關。
類似的還有如下類型:(點擊這裡)
size_t是unsigned類型,用於指明數組長度或下標,它必須是一個正數,std::size_t.設計size_t就是為了適應多個平台,其引入增強了程式在不同平台上的可移植性。
ptrdiff_t是signed類型,用於存放同一數組中兩個指標之間的差距,它可以使負數,std::ptrdiff_t.同上,使用ptrdiff_t來得到獨立於平台的地址差值.
size_type是unsigned類型,表示容器中元素長度或者下標,vector<int>::size_type i = 0;
difference_type是signed類型,表示迭代器差距,vector<int>:: difference_type = iter1-iter2.
前二者位於標準類庫std內,後二者專為STL對象所擁有。
//=====================================================================================
http://blog.csdn.net/yyyzlf/article/details/6209935
C and C++ define a special type for pointer arithmetic, namely ptrdiff_t, which is a typedef of a platform-specific signed integral type. You can use a variable of type ptrdiff_t to store the result of subtracting and
adding pointers.For example:
#include <stdlib.h>int main(){ int buff[4]; ptrdiff_t diff = (&buff[3]) - buff; // diff = 3 diff = buff -(&buff[3]); // -3}
What are the advantages of using ptrdiff_t? First, the name ptrdiff_t is self-documenting and helps the reader understand that the variable is used in pointer arithmetic exclusively. Secondly, ptrdiff_t is portable: its underlying type may vary across platforms,
but you don't need to make changes in the code when porting it.