为什么 sizeof(int) 在不同的操作系统中会有所不同? [英] Why does sizeof(int) vary across different operating systems?

查看:26
本文介绍了为什么 sizeof(int) 在不同的操作系统中会有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很奇怪为什么 int 的大小取决于使用哪个操作系统,在 C 和C++.如果指针的大小不同也没关系,但为什么整数的大小.如果 16 位 OS sizeof(int) = 2 字节,则对于 32 位 sizeof(int) = 4 字节.为什么会这样?

I wounder why size of int depends on which OS one is using ,in C & C++. It's ok if size of pointer varies, but why size of integer. If 16 bit OS sizeof(int) = 2 byte, for 32 bit sizeof(int) = 4 byte. Why so?

谢谢.

推荐答案

按照C++标准

1.7.1 状态:

C++ 内存模型中的基本存储单元是字节.一个字节至少足够大以包含基本的任何成员执行字符集...

The fundamental storage unit in the C++ memory model is the byte. A byte is at least large enough to contain any member of the basic execution character set ...

然后 3.9.1.1 状态:

then 3.9.1.1 states:

声明为字符(char)的对象应足够大以存储实现的基本字符集的任何成员.

Objects declared as characters (char) shall be large enough to store any member of the implementation’s basic character set.

所以我们可以推断出 char 实际上是一个字节.最重要的是 3.9.1.2 还说:

So we can infer that char is actually a byte. Most importantly 3.9.1.2 also says:

有五种有符号整数类型:signed char"、short int"、int"、long int"和long long int".在此列表中,每种类型提供至少与列表中前面的存储一样多.普通整数具有执行架构所建议的自然大小环境;提供其他有符号整数类型以满足特殊需要.

There are five signed integer types: "signed char", "short int", "int", "long int", and "long long int". In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment; the other signed integer types are provided to meet special needs.

换句话说,int 的大小 (a) 保证至少为一个字节,并且 (b) 自然与运行它的操作系统/硬件对齐,因此现在很可能是64 位或(对于许多旧系统)32 位.

So in other words the size of int is (a) guaranteed to be at least a byte and (b) naturally aligned to the OS/hardware it's running on so most likely these days to be 64 bit or (for many older systems) 32 bit.

这篇关于为什么 sizeof(int) 在不同的操作系统中会有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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