The sizeof operator yeilds the number of bytes required to store an object of the type of its operand.
sizeof(char) // = 1
sizeof(my_array) // = size of the array in bytes
sizeof(my_structure) // = size of the structure in bytes
sizeof(my_union) // = size of the union in bytes
for count = 0; count < (sizeof(my_array) / sizeof(my_array_tye)); count++)
{
//Do each entry in the array of a not necessarily known object size
Note that 16 and 32bit compilers may add padd bytes and these will be included in the sizeof – this can be a source of bugs!
Getting array length from sizeof
int Prices[5] = { 1, 2, 3, 4, 5 };
int Length = sizeof(Prices) / sizeof(Prices[0]);
Avoiding Padding
You can used the packed variable attribute. For example in the following code, type c_t will have a size of 3 bytes and there will be no wasted space between a and b:
typedef struct
{
unsigned char a[1];
} __attribute__ ((packed)) a_t;
typedef struct
{
unsigned char b[2];
} __attribute__ ((packed)) b_t;
typedef struct
{
a_t a;
b_t b;
} __attribute__ ((packed)) c_t;
