Search code examples
csizeof

Difference between sizeof(*p) and sizeof(p)?


I am using code below and getting different values.

int *p;

printf("Size of *p = %d", sizeof(*p));   // Here value is 4

printf("Size of p = %d", sizeof(p));    // Here value is 8

Can any one please explain, what exactly is the reason behind this?


Solution

  • For any pointer variable p, the variable p itself is the pointer and the size of it is the size of the pointer. *p is what p is pointing to, and the size of *p is the size of what is being pointed to.

    So when sizeof(p) reports 8 then you know that a pointer on your system is 8 bytes, and that you're probably on a 64-bit system.

    If sizeof(*p) reports 4 then you know that the size of int (which is what p is pointing to in your case) is 4 bytes, which is normal on both 32 and 64 bit systems.

    You would get the same result by doing sizeof(int*) and sizeof(int).

    Oh and a last note: To print the result of sizeof (which is of type size_t) then you should really use the "z" prefix, and an unsigned type specifier (since size_t is unsigned). For example "%zu". Not doing that is technically undefined behavior.