索引数组时我应该总是使用 size_t 吗? [英] Should I always use size_t when indexing arrays?

查看:63
本文介绍了索引数组时我应该总是使用 size_t 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否需要在索引数组时始终使用 size_t,即使数组不够大而无法超过 int 的大小?

Do I need to use size_t always when indexing an array even if the array is not big enough to exceed the size of an int?

这不是我应该何时使用 size_t 的问题.我只想知道,例如,一个程序是否有 2GB 的可用内存(所有这些字段都可以由 int32 索引),但是这个内存(虚拟内存)分配给了计算机的 14GB - 16GB 的字段"内存.

It's not a question about when I should use size_t. I just want to know if, for example, a program having 2GB of available memory (all of these fields can be indexed by an int32) but with this memory being (virtual memory) assigned to the "fields" 14GB - 16GB of the computer's RAM.

如果我在此使用 int32 而不是 size_t(或 unsigned long int),索引内存时会不会总是失败?案例?

Would it always fail when indexing the memory if I used an int32 instead of a size_t (or an unsigned long int) in this case?

也许问题更多的是关于虚拟内存而不是指针.

Maybe the question is more about virtual memory than about pointers.

推荐答案

size_t 是一个无符号整数,能够容纳您可以分配的最大对象的大小.它对索引很有用,因为这意味着它可以索引到您可以分配的最大数组.

size_t is an unsigned integer that is capable of holding the size of the largest object you can allocate. It is useful for indexing because this means it can index into the largest array you can allocate.

这并不意味着索引是必需的,甚至是推荐的.您可以使用任何足够大的整数类型来索引数组.int_fast32_t 可能更快,uint_least16_t 在结构中可能更小,依此类推.了解您的数据,您才能做出明智的选择.

This does not mean it is required or even necessarily recommended for indexing. You can use any integer type that is large enough to index the array. int_fast32_t might be faster, uint_least16_t might be smaller in a structure, and so on. Know your data, and you can make a good choice.

您应该考虑的一个问题是,在某些平台上,使用签名索引可能需要额外的符号扩展指令.例如,这里是 x86:

One consideration you should make is that on some platforms, using a signed index might require an extra sign extension instruction. As an example, here is x86:

// movzx eax, BYTE PTR [rcx+rdx]
// ret
char get_index(char *ptr, unsigned idx)
{
   return ptr[idx];
}

// ; sign extending idx from 32 bits to 64 bits with movsx here.
// movsx rdx, edx     
// movzx eax, BYTE PTR [rcx+rdx]
// ret
char get_index(char *ptr, int idx)
{
   return ptr[idx];
}

虚拟内存超出了 C 或 C++ 的范围.从他们的角度来看,您只需对内存进行索引,这取决于您的平台使其工作.实际上,您的应用程序仅使用虚拟地址;您的 CPU/OS 在幕后将虚拟地址转换为物理地址.这不是您需要担心的事情.

Virtual memory is outside the scope of C or C++. From their point of view, you simply index into memory and it's up to your platform to make it work. In practice your app only uses virtual addresses; your CPU/OS is translating the virtual address to a physical address behind the scenes. It is not something you need to worry about.

这篇关于索引数组时我应该总是使用 size_t 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆