sizeof Operators in C Programming





In C, the sizeof operator is used to determine the size, in bytes, of a data type or a variable. It's often used in conjunction with arrays, structs, and other data types to calculate the memory space they occupy.

The syntax for the sizeof operator is:

sizeof(type);
Or
sizeof(expression);

where type is a data type, and expression is any valid C expression.


Here are a few examples of how sizeof can be used:


  • To determine the size of a data type:

    #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 bytes
    
  • To determine the size of a variable:

    #include <stdio.h>
    
    int main() {
        int arr[10];
        printf("Size of the array: %zu bytes\n", sizeof(arr));
        return 0;
    }
    
    Output:
    Size of the array: 40 bytes
    
  • To determine the size of a struct:

    #include <stdio.h>
    
    struct Person {
        char name[20];
        int age;
    };
    
    int main() {
        printf("Size of struct Person: %zu bytes\n", sizeof(struct Person));
        return 0;
    }
    
Output:
Size of struct Person: 24 bytes