Why size of int pointer is different of size of int array? [duplicate]

一个人想着一个人 提交于 2019-12-01 07:45:46

问题


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.


回答1:


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.




回答2:


t is an int[3] type, not a pointer type.

So its size is 3 * sizeof(int).

In certain instances, t decays to a pointer, but this is not one of those instances.



来源:https://stackoverflow.com/questions/41699762/why-size-of-int-pointer-is-different-of-size-of-int-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!