int与size_t

来源:互联网 发布:淘宝店铺招牌950 120 编辑:程序博客网 时间:2024/05/21 12:41
size_t是一些C/C++标准在stddef.h中定义的。这个类型足以用来表示对象的大小。

size_t的真实类型与操作系统有关,在32位架构中被普遍定义为:

typedef unsignedint size_t;

而在64位架构中被定义为:

typedef unsigned long size_t;

size_t在32位架构上是4字节,在64位架构上是8字节,在不同架构上进行编译时需要注意这个问题。

而int在不同架构下都是4字节,与size_t不同;且int为带符号数,size_t为无符号数。


size_t is used to represent the size of any object (including arrays) in the particular implementation. It is used as the return type of thesizeof operator. The maximum size ofsize_t is provided viaSIZE_MAX, a macro constant which is defined in the<stdint.h> header (cstdint header in C++). It is guaranteed to be at least 65535.

Note that size_t is unsigned, signed sizes can be represented by ssize_t.


std::size_tsizeofalignof 操作符返回的一种无符号整数类型。

size_t 可以存放下理论上可能存在的对象的最大大小,该对象可以是任何类型,包括数组。在许多平台上(使用分段寻址的系统除外),std::size_t 可以存放下任何非成员的指针,此时可以视作其与std::uintptr_t 同义。

std::size_t 通常被用于数组索引和循环计数。使用其它类型来进行数组索引操作的程序可能会在某些情况下出错,例如在 64 位系统中使用unsignedint 进行索引时,如果索引号超过UINT_MAX 或者依赖于 32 位取模运算的话,程序就会出错。

在对诸如 std::stringstd::vector 等 C++ 容器进行索引操作时,正确的类型是该容器的成员 typedefsize_type,而该类型通常被定义为与std::size_t 相同。

示例

#include <cstddef>int main(){    const std::size_t N = 100;    int* a = new int[N];    for(std::size_t n = 0; n<N; ++n)        a[n] = n;    delete[] a;}