Why is the size of the int pointer different from the size of the int array?

Allows you to use the following code:

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

Then sizeof returns:

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

I believe that sizeof(t) is the result of 3 * sizeof(int) . But since t is a pointer to its first element, its size must be sizeof(p) .

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

Thanks.

+3
c arrays pointers sizeof
source share
2 answers

Because the variable t declared as having an array type

 int t[3]; 

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

C standard (6.5.3.4 sizeof and alignof operators)

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

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

In expressions with rare exceptions that are used in the sizeof operator descriptor, converters are converted to pointers to their first elements.

Thus, if you use, for example, the following expression

 sizeof( t + 0 ) 

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

From the C standard (6.3.2.1 Lvalues, arrays and function notation)

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

+8
source share

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

So its size is 3 * sizeof(int) .

In some cases, t splits into a pointer, but this is not one of these instances.

+12
source share

All Articles