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 ??
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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With