Understanding the sizeof Operator in C: Determining Memory Size

Learn about the sizeof operator in C, which allows you to get the memory size of different variable types. Discover how the memory size varies depending on the data type, enhancing your understanding of memory management in C programming.



C The sizeof Operator

Get the Memory Size

We introduced in the data types chapter that the memory size of a variable varies depending on the type:

Data Type Size
int 2 or 4 bytes
float 4 bytes
double 8 bytes
char 1 byte

The memory size refers to how much space a type occupies in the computer's memory.

Using the sizeof Operator

To actually get the size (in bytes) of a data type or variable, use the sizeof operator:

Example

int myInt;
float myFloat;
double myDouble;
char myChar;

printf("%lu\n", sizeof(myInt));
printf("%lu\n", sizeof(myFloat));
printf("%lu\n", sizeof(myDouble));
printf("%lu\n", sizeof(myChar));

Benifits of Size of Data Types:

Knowing the size of different data types is important because it provides details about memory usage and performance.

For example, the size of a char type is 1 byte. This means if you have an array of 1000 char values, it will occupy 1000 bytes (1 KB) of memory.

Using the right data type for the right purpose will save memory and improve the performance of your program.