Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

sizeof

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 ??

like image 553
Leo Messi Avatar asked Dec 04 '22 19:12

Leo Messi


1 Answers

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. :-)

like image 84
asveikau Avatar answered Dec 21 '22 12:12

asveikau