Every object has a
size in bytes, which is also the size of its
type. char
,
signed
char
and
unsigned
char
all
have a size of 1. You can get the size of an object using
the sizeof
operator:
int x;
printf("%zu\n", sizeof x);
printf("%zu\n", sizeof(int));
Brackets are required when offering a type name
instead of an expression. You can't offer an incomplete
type to sizeof
.
-
unary-expression
sizeof
unary-expression
sizeof (
type-name )
The result of a sizeof
expression is of type size_t
,
which is an alias for an unsigned
integer type with the range zero to SIZE_MAX
,
which is at least 65535. Use the type modifier
z on integer conversion specifiers with
printf
and scanf
to convert a size_t
to and from characters (for example, "%zu"
).
atomic_size_t
is an alias for _Atomic size_t
.
The size of an array is the size of each of its
elements times the number of elements, so you can get the
number of elements of an array arr
with an expression such as sizeof arr /
sizeof
arr[0]
.
The size of a structure type is the sum of the
sizes of its members plus padding for the sake of
alignment. The initial member
is assumed to be aligned for all types, then each member
is padded to ensure correct alignment of its subsequent
member, and the final member is padded for alignment of a
subsequent identical structure.
The size of a union type is the largest of the
sizes of its members plus padding for the sake of
alignment. For example, suppose
that sizeof(short)
is
2
and that alignof(short)
is
also 2
. This union could have a
size of 4, even though its largest member has a size of
3:
union foo {
short s;
char ca[3];
};
This is because the union as a whole must have a
suitable alignment for all its members (the highest
common factor, which is 2), and then each member must be
padded to be a multiple of that 2, so that an adjacent
union in an array will continue to have the same
alignment, and the maximum size of these padded members
is 4.