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

    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 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]);
}

    输出:

Infinite loop and then segmentation fault
参考文档

[1]Shubham Bansal.What is the size_t data type in C?[EB/OL].https://www.geeksforgeeks.org/size_t-data-type-c-language/,2020-07-17.

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值