sizeof() Operator in C

The sizeof() operator in C is used to determine the size (in bytes) of a data type or variable. It is a compile-time operator that returns the size of a data type or a variable in bytes. The size returned by the sizeof() operator can vary depending on the architecture of the system (32-bit vs 64-bit) and the data type being used.

Definition

The sizeof() operator is used to determine the memory size of a type or a variable. It can be applied to any data type, including built-in types like int, float, char, etc., as well as user-defined types such as structs, arrays, and pointers.

Syntax:

                        
sizeof(data_type_or_variable);
                        
                    

Example 1: Using sizeof() with Data Types

In this example, we use the sizeof() operator to find the size of different data types like int, float, and char.

Example:

                        
#include <stdio.h>
int main() 
{
    printf("Size of int: %zu bytes\n", sizeof(int));
    printf("Size of float: %zu bytes\n", sizeof(float));
    printf("Size of char: %zu bytes\n", sizeof(char));
        
    return 0;
}
                        
                    

Output

Size of int: 4 bytes
Size of float: 4 bytes
Size of char: 1 byte

Example 2: Using sizeof() with Variables

In this example, we use the sizeof() operator to find the size of variables rather than just data types.

Example:

                        
#include <stdio.h>
int main() 
{
    int num = 5;
    float pi = 3.14;
    char ch = 'A';
        
    printf("Size of num: %zu bytes\n", sizeof(num));
    printf("Size of pi: %zu bytes\n", sizeof(pi));
    printf("Size of ch: %zu bytes\n", sizeof(ch));
        
    return 0;
}
                        
                    

Output

Size of num: 4 bytes
Size of pi: 4 bytes
Size of ch: 1 byte

Example 3: Using sizeof() with Arrays

In this example, we use the sizeof() operator to determine the size of an array. Note that sizeof() returns the total size of the array, not the number of elements.

Example:

                        
#include <stdio.h>
int main() 
{
    int arr[5] = {1, 2, 3, 4, 5};
        
    printf("Size of arr: %zu bytes\n", sizeof(arr));
    printf("Size of one element of arr: %zu bytes\n", sizeof(arr[0]));
    printf("Number of elements in arr: %zu\n", sizeof(arr) / sizeof(arr[0]));
        
    return 0;
}
                        
                    

Output

Size of arr: 20 bytes
Size of one element of arr: 4 bytes
Number of elements in arr: 5

Key Points