我和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;?
当前回答
Size_t是无符号整数数据类型。在使用GNU C库的系统上,这将是unsigned int或unsigned long int。Size_t通常用于数组索引和循环计数。
其他回答
根据我的理解,size_t是一个无符号整数,其位大小足以容纳本机体系结构的指针。
So:
sizeof(size_t) >= sizeof(void*)
一般来说,如果从0开始向上,总是使用无符号类型,以避免溢出将您带入负值的情况。这是非常重要的,因为如果你的数组边界刚好小于你的循环的最大值,但你的循环最大值刚好大于你的类型的最大值,你将绕负,你可能会遇到分割错误(SIGSEGV)。所以,一般来说,对于从0开始并向上的循环,永远不要使用int。使用unsigned符号。
Since nobody has yet mentioned it, the primary linguistic significance of size_t is that the sizeof operator returns a value of that type. Likewise, the primary significance of ptrdiff_t is that subtracting one pointer from another will yield a value of that type. Library functions that accept it do so because it will allow such functions to work with objects whose size exceeds UINT_MAX on systems where such objects could exist, without forcing callers to waste code passing a value larger than "unsigned int" on systems where the larger type would suffice for all possible objects.
Size_t和int是不可互换的。例如,在64位Linux上size_t的大小是64位的(即sizeof(void*)),而int是32位的。
还要注意size_t是无符号的。如果你需要签名版本,那么在某些平台上有ssize_t,它与你的例子更相关。
作为一般规则,我建议在大多数情况下使用int,只有在特定需要时才使用size_t/ssize_t(例如mmap())。
types.h的manpage说:
Size_t应该是无符号整数类型