数组内存寻址的混乱
让我们有一个 int 类型的数组:-
int arr[5];
现在,
if arr[0] is at address 100 then
Why do we have;
arr[1] at address 102 ,
arr[2] at address 104 and so on.
不是
arr[1] at address 101 ,
arr[2] at address 102 and so on.
因为整数占用 2 个字节吗?
每个内存块是否有1 Byte容量(无论是32位处理器还是64位处理器)?
Lets have an array of type int:-
int arr[5];
Now,
if arr[0] is at address 100 then
Why do we have;
arr[1] at address 102 ,
arr[2] at address 104 and so on.
Instead of
arr[1] at address 101 ,
arr[2] at address 102 and so on.
Is it because an integer takes 2 bytes?
Does each memory block has 1 Byte capacity (whether it is 32 bit processor or 64 bit)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的第一个示例与 16 位
ints
一致。至于你的第二个例子 (
&arr[0]==100
,&arr[1]==101
,&arr[2]= =103
),这不可能是有效的布局,因为连续元素之间的距离在第一对和第二对之间有所不同。Your first example is consistent with 16-bit
ints
.As to your second example (
&arr[0]==100
,&arr[1]==101
,&arr[2]==103
), this can't possibly be a valid layout since the distance between consecutive elements varies between the first pair and the second.是的,
显然在您的系统上,
int
的大小为 2。在其他系统上,情况可能并非如此。通常int
的大小为 4 或 8 字节,但其他大小也是可能的。Yes
Apparently on your system,
int
has the size of 2. On other systems, this might not be the case. Usuallyint
is either sized 4 or 8 bytes, but other sizes are possible also.你是对的,在你的机器上,int 的 sizeof 是 2,所以数组中的下一个可能值将与前一个值相距 2 个字节。
对于
int
的大小没有任何保证。 C++ 规范只是说 sizeof(int) >= sizeof(char)。它取决于处理器、编译器等。有关更多信息尝试这个
You are right, on your machine the sizeof int is 2, so next possible value in the array will be 2 bytes away from the previous one.
There is no guaranty regarding size of
int
. C++ spec just says that sizeof(int) >= sizeof(char). It depends upon processor, compiler etc.For more info try this