說說size_t 和 ptrdiff_t

來源:互聯網
上載者:User

來源博文: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.


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.