数组内存寻址的混乱

发布于 2024-12-25 10:38:49 字数 424 浏览 2 评论 0原文

让我们有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

喜爱纠缠 2025-01-01 10:38:49

您的第一个示例与 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.

左岸枫 2025-01-01 10:38:49

是因为整数占用2个字节吗?

是的,

显然在您的系统上,int 的大小为 2。在其他系统上,情况可能并非如此。通常 int 的大小为 4 或 8 字节,但其他大小也是可能的。

It is because an integer takes 2 bytes?

Yes

Apparently on your system, int has the size of 2. On other systems, this might not be the case. Usually int is either sized 4 or 8 bytes, but other sizes are possible also.

淡水深流 2025-01-01 10:38:49

你是对的,在你的机器上,int 的 sizeof 是 2,所以数组中的下一个可能值将与前一个值相距 2 个字节。

-------------------------------
|100|101|102|103|104|105|106....
-------------------------------
arr[0]  arr[1]  arr[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.

-------------------------------
|100|101|102|103|104|105|106....
-------------------------------
arr[0]  arr[1]  arr[2]

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文