size"/>
C中的size
size_t是一种无符号整数数据类型,在各种头文件中定义,例如:
<stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h>
它是一种用于表示对象大小(以字节为单位)的类型,因此sizeof运算符将其用作返回类型。它需要足够大,以容纳主机系统能够处理的最大对象。基本上允许的最大大小取决于编译器:如果编译器是32位的,那么它是unsigned int的typedef(即别名),但是如果编译器是64位的,那么它将是unsigned long long的typedef。size_t数据类型从不为负。因此,许多C库函数(如malloc、memcpy和strlen)都将参数或返回类型声明为size_t。例如:
// Declaration of various standard library functions.// Here argument of 'n' refers to maximum blocks that can be
// allocated which is guaranteed to be non-negative.
void *malloc(size_t n);// While copying 'n' bytes from 's2' to 's1'
// n must be non-negative integer.
void *memcpy(void *s1, void const *s2, size_t n);// strlen() uses size_t because the length of any string
// will always be at least 0.
size_t strlen(char const *s);
size_t或任何unsigned类型都可能被用作循环变量,因为循环变量通常大于或等于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>#define N 10int main()
{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 they can lead to infinite loops.for (size_t n = N-1; n >= 0; --n)printf("%d ", a[n]);
}
输出:
Infinite loop and then segmentation fault
参考文档
[1]Shubham Bansal.What is the size_t data type in C?[EB/OL]./,2020-07-17.
更多推荐
C中的size
发布评论