3

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.

LPs
  • 16,045
  • 8
  • 30
  • 61
intermet
  • 89
  • 1
  • 6
  • 3
    Because pointer is pointer and array is array. Why the size of a house is different than the size of piece of paper its address is written on? – Eugene Sh. Jan 17 '17 at 14:33
  • 2
    "But as t is a pointer to his first element" this is false, `t` is an array, if you dereference it, you'll get the first element, that doesn't mean it has to be a pointer. – George Jan 17 '17 at 14:33
  • 1
    It is true that an array can *decay* to a pointer to its first element, but an array in itself is not a pointer. – Some programmer dude Jan 17 '17 at 14:34

2 Answers2

13

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
8

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335