博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
size_t、ptrdiff_t【转】
阅读量:7101 次
发布时间:2019-06-28

本文共 1740 字,大约阅读时间需要 5 分钟。

转自:

对于指向同一数组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 
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.

你可能感兴趣的文章
Debian出现in the drive ‘/media/cdrom/’ and press enter解决办法
查看>>
SkRefCnt
查看>>
1.把一个字符串内的正整数相加
查看>>
日记(二)
查看>>
list,tuple,set,dict基础
查看>>
PIC中的#pragma idata 和#pragma udata
查看>>
使用FileAudit在Windows服务器上实现最优文件访问监控
查看>>
mysql 远程连接数据库的二种方法
查看>>
一步一步学android OpenGL ES2.0编程(4)
查看>>
corosync 源代码分析1
查看>>
寻找Cydia里面软件安装包deb文件的真实下载地址
查看>>
如何收缩日志文件
查看>>
解决Excel打开UTF-8编码的CSV文件乱码的问题
查看>>
Powershell invoke-command vs -computerName 效率比较
查看>>
送给那些有代码基础但仍旧不会学自动化测试的朋友们
查看>>
做公关必用的四大法宝
查看>>
Microsoft Hyper-V Server 2012开启虚拟化-虚拟机管理
查看>>
Linux下Oracle设置环境变量
查看>>
VBScript的字符串方法
查看>>
C和汇编调用一例
查看>>