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!

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;
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.