导航

【转】size_t和ssize_t

Posted on 2012-02-08 21:29  网名还没想好  阅读(2200)  评论(1编辑  收藏  举报

ssize_t是什么类型的?

解释一:为了增强程序的可移植性,便有了size_t,它是为了方便系统之间的移植而定义的,不同的系统上,定义size_t可能不一样。

     在32位系统上 定义为 unsigned int 也就是说在32位系统上是32位无符号整形。在64位系统上定义为 unsigned long 也就是说在64位系统上是64位无符号整形。size_t一般用来表示一种计数,比如有多少东西被拷贝等。例如:sizeof操作符的结果类型是size_t,该类型保证能容纳实现所建立的最大对象的字节大小。 它的意义大致是“适于计量内存中可容纳的数据项目个数的无符号整数类型”。所以,它在数组下标和内存管理函数之类的地方广泛使用。而ssize_t这个数据类型用来表示可以被执行读写操作的数据块的大小.它和size_t类似,但必需是signed.意即:它表示的是signed size_t类型的。

typedef unsigned long size_t

解释二:ssize_t是signed size_t,

size_t是标准C库中定义的,应为unsigned int。定义为typedef int ssize_t。

而ssize_t:这个数据类型用来表示可以被执行读写操作的数据块的大小.它和size_t类似,但必需是signed.意即:它表示的是sign size_t类型的。

《Unix 高级环境编程》里面是这么说的:

原始系统数据类型
前面所示的g e t p i d函数的原型定义了其返回值为p i d _ t类型,这也是P O S I X中的新规定。
U N I X的早期版本规定此函数返回一整型。与此类似, r e a d和w r i t e返回类型为s s i z e _ t的值,并
要求第三个参数的类型是s i z e _ t。
以_ t结尾的这些数据类型被称为原始系统数据类型。它们通常在头文件< s y s / t y p e s . h >中定
义(头文件< u n i s t d . h >应已包括该头文件)。它们通常以C typedef说明加以定义。t y p e d e f说明在C
语言中已超过1 5年了(所以这并不要求ANSI C),它们的目的是阻止程序使用专门的数据类型
(例如i n t , s h o r t或long) 来允许对于一种特定系统的每个实现选择所要求的数据类型。在需要存储
进程I D的地方,分配类型为p i d _ t的一个变量(注意,程序1 - 5已对名为p i d的变量这样做了)。在
各种不同的实现中,这种数据类型的定义可能是不同的,但是这种差别现在只出现在一个头文
件中。我们只需在另一个系统上重新编辑应用程序。

 This's a way of defining size_t and ssize_t in Linux:

 //"linux/types.h"
 typedef __kernel_size_t size_t;
 typedef __kernel_ssize_t ssize_t;
 //"asm/posix_types.h"
typedef unsigned int __kernel_size_t;
 typedef int __kernel_ssize_t;

 It seems so tricky to me. What benefits do we get from such a tricky
 typedef ? better name (size_t is shorter than unsigned int) ?[/color]

On some 64-bit platforms, 'int' and 'unsigned int' may be 32-bits,
while addresses and even memory sizes could require 64 bits
(e.g. for the size of an allocated memory block > 4GB).
On such platforms, size_t could be typedef'd to a different
type, such as 'unsigned long long'.

Note also that 'size_t' is a typedef required by the ISO C standard
(it must be available if <stddef.h> is included). However, 'ssize_t'
does not exist in the C standard -- the standard 'ptrdiff_t'
typedef is nearly equivalent.