为什么int指针的大小与int数组的大小不同? [英] Why size of int pointer is different of size of int array?

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

问题描述

下面是代码:

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 sizeof运算符产生其操作数的大小(以字节为单位),

实际上,具有三个类型为int的元素的数组占用的内存字节数等于3 * sizeof( int ).

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

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

sizeof( t + 0 )

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

根据C标准(6.3.2.1左值,数组和函数指示符)

3 除非它是sizeof运算符的操作数或一元& 运算符,或者是用于初始化数组的字符串文字, 类型为类型数组"的表达式将转换为 类型为要输入的指针"的表达式指向初始 数组对象的元素,不是左值.如果数组对象 具有寄存器存储类,其行为未定义.

Lets be the following code:

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

Then sizeof returns:

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

I suppose that sizeof(t) is the result of 3 * sizeof(int). But as t is a pointer to his first element, its size should be sizeof(p).

Why sizeof(t) returns the size of the memory block which represents the array ?

Thanks.

解决方案

As the variable t is declared as having an array type

int t[3];

then sizeof( t ) yields a value equal to 3 * sizeof( int )

The C Standard (6.5.3.4 The sizeof and alignof operators)

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

and indeed an array with three elements of type int occupies memory equal in bytes to 3 * sizeof( int ).

In expressions with rare exceptions as using in the sizeof operator array designators are converted to pointers to their first elements.

Thus if you will use for example the following expression

sizeof( t + 0 )

then t in the expression t + 0 will be converted to pointer and you will get that sizeof( t + 0 ) is equal to the size of a pointer to int on your platform, which is 8.

From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

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 undefined.

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

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