我和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*)
其他回答
types.h的manpage说:
Size_t应该是无符号整数类型
Size_t是一种无符号整型数据类型,它只能赋0和大于0的整型值。它测量任何对象大小的字节,并由sizeof操作符返回。
Const是size_t的语法表示,但是没有Const你也可以运行程序。
const size_t number;
Size_t经常用于数组索引和循环计数。如果编译器是32位的,它将在unsigned int上工作。如果编译器是64位的,它也可以在unsigned long long int上工作。size_t的最大大小取决于编译器类型。
Size_t已经在<stdio.h>头文件中定义,但它也可以由 <stddef.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h>头文件。
示例(使用const)
#include <stdio.h>
int main()
{
const size_t value = 200;
size_t i;
int arr[value];
for (i = 0 ; i < value ; ++i)
{
arr[i] = i;
}
size_t size = sizeof(arr);
printf("size = %zu\n", size);
}
输出:size = 800
示例(不含const)
#include <stdio.h>
int main()
{
size_t value = 200;
size_t i;
int arr[value];
for (i = 0; i < value; ++i)
{
arr[i] = i;
}
size_t size = sizeof(arr);
printf("size = %zu\n", size);
}
输出:size = 800
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.
从维基百科:
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是保证保存任何数组下标的类型。
Size_t是无符号整数数据类型。在使用GNU C库的系统上,这将是unsigned int或unsigned long int。Size_t通常用于数组索引和循环计数。