我和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是一个无符号整数,其位大小足以容纳本机体系结构的指针。
So:
sizeof(size_t) >= sizeof(void*)
其他回答
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是一种可以保存任何数组下标的类型。
根据实现的不同,它可以是:
它没有查尔
无符号短
无符号整型
无符号长
未签名的long long
下面是在我的机器的stddef.h中如何定义size_t:
typedef unsigned long size_t;
根据我的理解,size_t是一个无符号整数,其位大小足以容纳本机体系结构的指针。
So:
sizeof(size_t) >= sizeof(void*)
Size_t是无符号类型。因此,它不能表示任何负值(<0)。当你在计算某物,并且确定它不是负的时候,你就会用到它。例如,strlen()返回size_t,因为字符串的长度必须至少为0。
在您的示例中,如果循环索引总是大于0,那么使用size_t或任何其他无符号数据类型可能是有意义的。
当使用size_t对象时,必须确保在使用它的所有上下文中(包括算术)都需要非负值。例如,假设你有:
size_t s1 = strlen(str1);
size_t s2 = strlen(str2);
你想求出str2和str1的长度之差。你不能:
int diff = s2 - s1; /* bad */
这是因为赋给diff的值总是一个正数,即使s2 < s1,因为计算是用无符号类型完成的。在这种情况下,根据您的用例,对于s1和s2使用int(或long long)可能会更好。
C/POSIX中有一些函数可以/应该使用size_t,但由于历史原因不使用。例如,fgets的第二个参数理想情况下应该是size_t,但它是int。
Size_t或任何无符号类型可能被视为循环变量,因为循环变量通常大于或等于0。
当使用size_t对象时,必须确保在使用它的所有上下文中(包括算术)只需要非负值。例如,下面的程序肯定会给出意想不到的结果:
// C program to demonstrate that size_t or
// any unsigned int type should be used
// carefully when used in a loop
#include<stdio.h>
int main()
{
const size_t N = 10;
int a[N];
// This is fine
for (size_t n = 0; n < N; ++n)
a[n] = n;
// But reverse cycles are tricky for unsigned
// types as can lead to infinite loop
for (size_t n = N-1; n >= 0; --n)
printf("%d ", a[n]);
}
Output
Infinite loop and then segmentation fault