我和c中的size_t搞混了,我知道它是由sizeof操作符返回的。但它究竟是什么?它是数据类型吗?
假设我有一个for循环:
for(i = 0; i < some_size; i++)
我应该用int I吗?或者size_t i;?
我和c中的size_t搞混了,我知道它是由sizeof操作符返回的。但它究竟是什么?它是数据类型吗?
假设我有一个for循环:
for(i = 0; i < some_size; i++)
我应该用int I吗?或者size_t i;?
当前回答
如果你是经验主义者,
echo | gcc -E -xc -include 'stddef.h' - | grep size_t
输出Ubuntu 14.04 64位GCC 4.8:
typedef long unsigned int size_t;
注意,stddef.h是由GCC提供的,而不是GCC 4.2中src/ GCC /ginclude/stddef.h下的glibc。
有趣的C99外观
Malloc以size_t作为参数,因此它决定了可以分配的最大大小。 由于它也是由sizeof返回的,我认为它限制了任何数组的最大大小。 请参见:C语言中数组的最大大小是多少?
其他回答
Size_t是无符号整数数据类型。在使用GNU C库的系统上,这将是unsigned int或unsigned long int。Size_t通常用于数组索引和循环计数。
这是一个平台特定的类型定义。例如,在特定的机器上,它可能是unsigned int或unsigned long。您应该使用这个定义来提高代码的可移植性。
Size_t是一种可以保存任何数组下标的类型。
根据实现的不同,它可以是:
它没有查尔
无符号短
无符号整型
无符号长
未签名的long long
下面是在我的机器的stddef.h中如何定义size_t:
typedef unsigned long size_t;
types.h的manpage说:
Size_t应该是无符号整数类型
从维基百科:
According to the 1999 ISO C standard (C99), size_t is an unsigned integer type of at least 16 bit (see sections 7.17 and 7.18.3). size_tis an unsigned data type defined by several C/C++ standards, e.g. the C99 ISO/IEC 9899 standard, that is defined in stddef.h.1 It can be further imported by inclusion of stdlib.h as this file internally sub includes stddef.h. This type is used to represent the size of an object. Library functions that take or return sizes expect them to be of type or have the return type of size_t. Further, the most frequently used compiler-based operator sizeof should evaluate to a constant value that is compatible with size_t.
作为暗示,size_t是保证保存任何数组下标的类型。