Need of Sizeof

1. To find out the number of elements in an array: Sizeof can be used to calculate the number of elements of the array automatically. 

Example:

C




// C Program
// demonstrate the method
// to find the number of elements
// in an array
#include <stdio.h>
int main()
{
    int arr[] = { 1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14 };
    printf("Number of elements:%lu ",
           sizeof(arr) / sizeof(arr[0]));
    return 0;
}


Output

Number of elements:11 

2. To allocate a block of memory dynamically: sizeof is greatly used in dynamic memory allocation. For example, if we want to allocate memory that is sufficient to hold 10 integers and we don’t know the sizeof(int) in that particular machine. We can allocate with the help of sizeof. 

Syntax:

int* ptr = (int*)malloc(10 * sizeof(int));

For more information, refer to the article – Allocate a Block of Memory Dynamically.



sizeof operator in C

Sizeof is a much-used operator in the C. It is a compile-time unary operator which can be used to compute the size of its operand. The result of sizeof is of the unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data type, including primitive types such as integer and floating-point types, pointer types, or compound datatypes such as Structure, union, etc.

Syntax:

sizeof(Expression);

where ‘Expression‘ can be a data type or a variable of any type.

Return: It returns the size size of the given expression.

Time Complexity: O(1)
Auxiliary Space: O(1)

Similar Reads

Usage of sizeof() operator

sizeof() operator is used in different ways according to the operand type....

Type of operator

...

Need of Sizeof

...