sinbad said:
how to make sizeof return unpadded struct size;
"Unpadded struct size" is a meaningless phrase, since the size of the
struct is an unqualified concept. However, I think I know what you mean.
See blow.
struct abc {
int z;
int y;
char x;
};
sizeof(struct abc) returns 12 padding 3 bytes for x;
sizeof(struct abc) returns the size of the struct. Period.
But i need a way to determine the real unpadded size of struct abc
which is 9;
And "real unpadded size" is meaningless. The real size of the struct is
the value returned by sizeof. Its reality as the struct size is
unqualified.
one way is to compute it statically, it there any other way for this?
It seems clear that you have no interest in the size of struct abc.
It seems that what you want is something completely differemt, the sum
of the sizes of the named and visible members of that struct. The answer
is clear: add together the sizes of the members of the struct:
#include <stdio.h>
struct abc
{
int z;
int y;
char x;
};
int main(void)
{
struct abc foo;
printf("On this implementation, a struct abc takes %zu bytes.\n\n",
sizeof(struct abc));
printf("Here is a poor way to determine the size of the members\n"
"Using a null pointer to a non-existent instance of"
" the struct.\n"
"The member z takes %zu bytes.\n"
"The member y takes %zu bytes.\n"
"The member x takes %zu bytes.\n"
"The sum of these is %zu bytes.\n\n",
sizeof(((struct abc *) 0)->z),
sizeof(((struct abc *) 0)->y),
sizeof(((struct abc *) 0)->x),
sizeof(((struct abc *) 0)->z) +
sizeof(((struct abc *) 0)->y) +
sizeof(((struct abc *) 0)->x));
printf("The better way is to use an actual instance.\n"
"The member z takes %zu bytes.\n"
"The member y takes %zu bytes.\n"
"The member x takes %zu bytes.\n"
"The sum of these is %zu bytes.\n\n",
sizeof foo.z,
sizeof foo.y,
sizeof foo.x,
sizeof foo.z +
sizeof foo.y +
sizeof foo.x);
return 0;
}
On this implementation, a struct abc takes 12 bytes.
Here is a poor way to determine the size of the members
Using a null pointer to a non-existent instance of the struct.
The member z takes 4 bytes.
The member y takes 4 bytes.
The member x takes 1 bytes.
The sum of these is 9 bytes.
The better way is to use an actual instance.
The member z takes 4 bytes.
The member y takes 4 bytes.
The member x takes 1 bytes.
The sum of these is 9 bytes.