Why is sizeof(type) the size of a pointer, not the size of the type itself?

c, sizeof

Solution

Because C says:

(C99, 6.2.1p7) "Any other identifier has scope that begins just after the completion of its declarator."

So in your example, the scope of the object `x` start right after the `x *x`:

x *x = /* scope of object x starts here */
       malloc(sizeof(x));

To convince yourself, put another object declaration of type `x` right after the declaration of the object `x`: you will get a compilation error:

void foo(void)
{
    x *x = malloc(sizeof(x));  // OK
    x *a;   // Error, x is now the name of an object
}

Otherwise, as Shahbaz notee in the comments of another answer, this is still not a correct use of `malloc`. You should call `malloc` like this:

T *a = malloc(sizeof *a);

and not

T *a = malloc(sizeof a);

Problem

In this code, why is `sizeof(x)` the size of a pointer, not the size of the type `x`? ``` typedef struct { ... } x; void foo() { x *x = malloc(sizeof(x)); } ```

Original source