C Language | Structure Declarations | Type Size - sizeof

Use the sizeof operator to obtain the storage size required for a value or an instance of a defined type.

Obtaining the Size of a Value

Memory space is allocated to every variable and to each instance of a structure or union. For example, an int typically occupies four bytes on a 32-bit computer. Although modern systems have much more memory than older systems, memory remains an important consideration in programming.

In C, use the sizeof operator to check the size of a variable or type. It returns the number of bytes required by the specified value. The resulting integer can be used in pointer operations and structure-related processing.

sizeof Operator

sizeof expression

This form obtains the size of the value specified by an expression. The expression is commonly an identifier such as a variable name.

Code 1

#include <stdio.h>

int main() {
 char c;
 short si;
 int i;

  printf("char = %d : short = %d : int = %d\n" ,
   sizeof c , sizeof si , sizeof i
 );
  return 0;
}

Code 1 displays the sizes of a char variable named c, a short variable named si, and an int variable named i. The results depend on the system, but the size of char is always 1. On a typical 32-bit computer, int is expected to occupy four bytes and short two bytes. The sizeof operator lets you confirm the exact sizes used by your system.

Creating unused variables only to check type sizes is unnecessary. The sizeof operator can also receive a parenthesized type name.

sizeof Operator with a Type

sizeof (type-specifier)

You can specify structure types and typedef names as well as basic types.

Code 2

#include <stdio.h>

typedef struct { int x , y; } Point;
typedef union {
  char c;
 short si;
 int i;
} Value;

int main() {
  printf("Point = %d : Value = %d\n" , sizeof(Point) , sizeof(Value));
 return 0;
}

Code 2 passes types to the sizeof operator. It obtains the byte sizes of the Point structure and the Value union. The size of Point is equivalent to sizeof (int) * 2, while the size of Value is equivalent to the size of its largest member, int.