📜  C中的size_t数据类型是什么?

📅  最后修改于: 2021-05-25 18:40:41             🧑  作者: Mango

size_t是无符号整数数据类型,在各种头文件中定义,例如:

, , , , , 

它是一种类型,用于表示对象的大小(以字节为单位),因此由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或任何无符号类型都可能被视为循环变量,因为循环变量通常大于或等于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
  
#define N 10
  
int 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]);
}
Output
Infinite loop and then segmentation fault
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”