can any one give rule behind the how structure byte padding works
There can be padding after any element, including the last.
(Bit-field elements are special, and complicated, so let's just
ignore them -- besides, you can't point at them anyhow, so their
position within the larger struct doesn't matter much.)
Is it depends on machine word size or size of the largest data type or
something else.
The implementation is free to use as much or as little padding
as it wants, and to arrange the padding any way it wants, provided
any padding bytes come after struct elements (that is, there can be
no padding before the first element). Usually, an implementation
will insert the smallest amount of padding necessary to satisfy the
alignment requirements of the element's own type. For example, on
a system where a `double' is eight bytes long and must be aligned
on a four-byte boundary, the struct
struct s { char x; double y; char z; };
.... will probably have six padding bytes: three after `x' so that
`y' begins four bytes in (and will be four-byte-aligned if the
struct itself is), and another three after `z' so that in an array
of `struct s' objects the second array element will be four-byte-
aligned if the array itself is. If you want to discover how a given
implementation has padded a given struct, you can use the offsetof()
macro from <stddef.h>:
printf ("struct s takes %d bytes\n", (int)sizeof(struct s));
printf ("x starts %d bytes in\n", (int)offsetof(struct s, x));
printf ("y starts %d bytes in\n", (int)offsetof(struct s, y));
printf ("z starts %d bytes in\n", (int)offsetof(struct s, z));
However, the alignment requirements for various data types are
also entirely up to the implementation. Thus, different compilers
may pad the same source-code struct differently to satisfy their
differing alignment needs, and the values printed by this code may
differ from one system to another. (Except that the offset of `x'
will always be zero; no padding before the first element.)