加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么int指针的大小与int数组的大小不同?

发布时间:2020-12-16 10:49:43 所属栏目:百科 来源:网络整理
导读:参见英文答案 How to find the ‘sizeof’ (a pointer pointing to an array)?????????????????????????????????????13个 让我们以下代码: int x;int *p = x;int t[3]; 然后sizeof返回: sizeof(x) - 4sizeof(p) - 8sizeof(t) - 12 我认为sizeof(t)是3 * si
参见英文答案 > How to find the ‘sizeof’ (a pointer pointing to an array)?????????????????????????????????????13个
让我们以下代码:

int x;
int *p = &x;
int t[3];

然后sizeof返回:

sizeof(x) -> 4
sizeof(p) -> 8
sizeof(t) -> 12

我认为sizeof(t)是3 * sizeof(int)的结果.
但由于t是指向其第一个元素的指针,因此其大小应为sizeof(p).

为什么sizeof(t)返回代表数组的内存块的大小?

谢谢.

解决方法

由于变量t被声明为具有数组类型

int t[3];

然后sizeof(t)产生一个等于3 * sizeof(int)的值

C标准(6.5.3.4 sizeof和alignof运算符)

2 The sizeof operator yields the size (in bytes) of its operand,

实际上,一个包含三个int类型元素的数组占用内存,以字节为单位,等于3 * sizeof(int).

在少数例外的表达式中,因为在sizeof运算符中使用数组指示符将转换为指向其第一个元素的指针.

因此,如果您将使用例如以下表达式

sizeof( t + 0 )

那么表达式t 0中的t将转换为指针,你将得到sizeof(t 0)等于你平台上指向int的指针的大小,即8.

来自C标准(6.3.2.1 Lvalues,数组和函数指示符)

3 Except when it is the operand of the sizeof operator or the unary & operator,or is a string literal used to initialize an array,an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class,the behavior is unde?ned.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读