Reputation: 37
I have a structure like this What would be the output of sizeof function.
struct sample
{
int a;
char b;
};
struct sample obj;
struct sample * ptr;
sizeof(*ptr);
I tried this piece of code in C using gcc compiler and that gave me the size of the structure itself. But i'm doubtful whether this would yield the same result when tried with other C compilers and also with C++.
Could you please help me on this.
Thanks in advance.
Upvotes: 0
Views: 2516
Reputation: 170064
I tried this piece of code in C using gcc compiler and that gave me the size of the structure itself
As it should. The argument to the unary sizeof
operator can be either an expression or a parenthesized type name. All expressions in C have a type. And what sizeof
is meant do is to look at the type the expression would evaluate to, and give the size of that type.
Since *ptr
is an expression of the type struct sample
, the result should be the size of struct sample
. It's also worth mentioning that generally the expression doesn't even need to be evaluated, the size can be determined statically (unless you are dealing with a VLA).
You can rely on that behavior, because that's what the C standard specifies it should do. It will always give the size of the structure. You can't rely on the size being the same across compilers, but you can be sure of the behavior sizeof
will have.
Since your own example uses pointers, one place where this behavior can be useful is described in "Do I cast the result of malloc?", where you'd feed malloc
the size of the dereferenced pointer, instead of the type:
struct sample * ptr = malloc(sizeof *ptr);
The rationale being that you don't need to repeat the type name twice (thrice in C++, where you'd need a cast as well), helping you to avoid subtle mistakes that may come when refactoring.
Upvotes: 10