Leo Messi
Leo Messi

Reputation: 822

Difference between sizeof(*ptr) and sizeof(struct)

I tried the following program

struct temp{
   int ab;
   int cd;
};

int main(int argc, char **argv)
{
   struct temp *ptr1;
   printf("Sizeof(struct temp)= %d\n", sizeof(struct temp));
   printf("Sizeof(*ptr1)= %d\n", sizeof(*ptr1));
   return 0;
}

Output

Sizeof(struct temp)= 8
Sizeof(*ptr1)= 8

In Linux I have observed at many places the usage of sizeof(*pointer). If both are same why is sizeof(*pointer) used ??

Upvotes: 4

Views: 7786

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477010

sizeof works in one of two ways: 1) with a type, 2) with an expression. The latter case is identical to calling sizeof on the type of the expression.

So you can write this:

int a;

char p[sizeof(int)];
char q[sizeof a];

Both mean the same thing.

The utility of the expression version for declaring a pointer to dynamic memory is that you only need to spell out the type once:

complex_type * pc = malloc(sizeof(*pc) * 100); // room for 100 elements

If you later choose to change the type of *pc, you only have to change the code in one single place.

Upvotes: 1

asveikau
asveikau

Reputation: 40226

I generally prefer sizeof(*ptr) because if you later go back and change your code such that ptr now has a different type, you don't have to update the sizeof. In practice, you could change the type of ptr without realizing that a few lines further down, you're taking the structure's size. If you're not specifying the type redundantly, there's less chance you'll screw it up if you need to change it later.

In this sense it's one of those "code for maintainability" or "code defensively" kind of things.

Others may have their subjective reasons. It's often fewer characters to type. :-)

Upvotes: 15

Related Questions