[英]Why size_t is used for indexing / representing size of an array?
According to C++ - should you size_t with a regular array?根据C++ - 你应该用常规数组 size_t 吗?
§ 18.2 6 The type size_t is an implementation-defined unsigned integer type that is large enough to contain the size in bytes of any object.
§ 18.2 6 类型 size_t 是实现定义的无符号整数类型,它足够大以包含任何对象的字节大小。
I don't understand why this guarantees a type size_t
to be big enough for an array index or big enough to represent the number of elements in an array.我不明白为什么这保证了
size_t
类型对于数组索引足够大或足够大以表示数组中的元素数量。
For example:例如:
int array[1000];
for (size_t i = 0; i < 1000; ++i) {
}
It seems unrelated to me why a "large enough number to contain the size in bytes of an object" == guarantees a type size_t
to be big enough for an array index".为什么“足够大的数字可以包含对象的字节大小”==保证类型
size_t
对数组索引足够大,这似乎与我无关。
It simply means, the largest array supported by the platform will be indexable with size_t
.这只是意味着,平台支持的最大数组将可以使用
size_t
进行索引。
Consider:考虑:
int array[1000];
for (uint8_t i; i < 1000; ++i) {}
This is clearly wrong, uint8 does not have range to index that array.这显然是错误的,uint8 没有索引该数组的范围。
size_t
does, always, guaranteed by the standard. size_t
总是由标准保证。
As to why it is bytes, using sizeof array
gives byte size.至于为什么是字节,使用
sizeof array
给出字节大小。 There needs to be a type guaranteed to be able to represent the result.需要有一种类型保证能够表示结果。
I guess it would make more technical sense to use ptrdiff_t
to index arrays, because that is what array index kind of is: *(array+index)
.我想使用
ptrdiff_t
来索引数组会更具有技术意义,因为这就是数组索引的类型: *(array+index)
。 But that's not so common, I guess it looks uglier, is longer to type and may be more confusing.但这并不常见,我想它看起来更丑,打字时间更长,可能更令人困惑。
Note that C++ standard does not make any similar guarantees about any other type.请注意,C++ 标准不对任何其他类型做出任何类似的保证。 But this range issue is somewhat theoretical in most practical cases, as you can be sure that a 64 bit integer can also index anything that fits in the memory.
但是在大多数实际情况下,这个范围问题有点理论化,因为您可以确定 64 位整数也可以索引任何适合内存的内容。 It's more important for communicating intent.
这对于传达意图更为重要。
An array is an object.数组是一个对象。 If
size_t
can represent the size of the array in bytes, then it can also surely represent any index into it, since an individual element has at least one byte size.如果
size_t
可以以字节为单位表示数组的大小,那么它肯定也可以表示其中的任何索引,因为单个元素至少有一个字节大小。
An array with a larger size than that is simply not allowed by the language.该语言根本不允许使用大于该大小的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.