size_t、ptrdiff_t


http://longzxr.blog.sohu.com/196837377.html

對於指向同一數組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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM