C中的size

编程入门 行业动态 更新时间:2024-10-14 02:21:51

C中的<a href=https://www.elefans.com/category/jswz/34/1761251.html style=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

本文发布于:2024-03-13 19:22:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1734642.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:size

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!