数组指针的大小 [英] Sizeof Pointer to Array

查看:127
本文介绍了数组指针的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个这样的数组:

  int a [3] [2] 

那么为什么是:

  sizeof(a + 0)== 8 



< >

  sizeof(a)== 24 

我不明白如何添加0到指针改变 sizeof 输出。

如果你添加 0 ,那么可能会有一些隐式类型转换?

a ,然后 a 首先转换为 int(*)类型的指针值[2] (指向 int [3] [2] 的数组的第一个元素。然后 0 被添加到它,它将 0 * sizeof(int [2])那个指针的值。由于该乘法产生0,它将产生相同的指针值。因为它是一个指针, sizeof(a + 0)产生一个指针的大小,这是你的框上的8个字节。



如果你执行 sizeof(a),编译器没有理由转换 a 到一个指针值(只有当你想索引元素或做涉及元素地址的指针运算时才有意义)。因此,表达式 a 保持为数组类型,而改为 int [3] [2] 大小 int(*)[2] 。所以,你的框上的 3 * 2 * sizeof(int)是24字节。



希望这澄清事情。


If I have an array declared like this:

int a[3][2];

then why is:

sizeof(a+0) == 8

whereas:

sizeof(a)   == 24

I don't understand how adding 0 to the pointer changes the sizeof output. Is there maybe some implicit type cast?

解决方案

If you add 0 to a, then a is first converted to a pointer value of type int(*)[2] (pointing to the first element of an array of type int[3][2]). Then 0 is added to that, which adds 0 * sizeof(int[2]) bytes to the address represented by that pointer value. Since that multiplication yields 0, it will yield the same pointer value. Since it is a pointer, sizeof(a+0) yields the size of a pointer, which is 8 bytes on your box.

If you do sizeof(a), there is no reason for the compiler to convert a to a pointer value (that makes only sense if you want to index elements or to do pointer arithmetic involving the address of the elements). So expression a stays being of an array type, and you get the size of int[3][2] instead the size of int(*)[2]. So, 3 * 2 * sizeof(int) which on your box is 24 bytes.

Hope this clarifies things.

这篇关于数组指针的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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