问题
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 ??
回答1:
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. :-)
回答2:
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.
来源:https://stackoverflow.com/questions/7757870/difference-between-sizeofptr-and-sizeofstruct