C programming language provides the sizeof()
function or operation in order to get the size of the specified variable, array, or object. The sizeof is very popular and used in different ways with different scenarios. The sizeof is very useful to get an object size in order to allocate required memory.
sizeof() Syntax
The sizeof() syntax is like below which only takes a single parameter in order to return size. The sizeof() returns the size as an integer as a byte count.
sizeof(OBJECT)
- OBJECT is a variable, an array, object, or expression.
Size of Data Type
The sizeof can be used to get the size of an object or data type. In the following example, we print different types of sizes like char, int, float, and double.
#include <stdio.h>
int main()
{
printf("Size of char is %lu\n", sizeof(char));
printf("Size of int is %lu\n", sizeof(int));
printf("Size of float is %lu\n", sizeof(float));
printf("Size of double is %lu", sizeof(double));
return 0;
}
Size of Expression
The sizeof() can be used to get the size of expressions. Keep in mind that the expression should not be dynamic and executed compilation time as the sizeof() is an compile-time operator.
#include <stdio.h>
int main()
{
int a = 5;
double b = 10.99;
printf("Size of expression is %lu", sizeof(a + b));
return 0;
}
Size of Array
Another popular use case for the sizeof() is getting the element count of the array by dividing the array total size by the data type size.
#include <stdio.h>
int main()
{
int a[] = { 1, 2, 3, 4 };
printf("Number of elements:%lu ", sizeof(a) / sizeof(a[0]));
return 0;
}
Using Size of Memory Allocation
Another case is calculating the memory allocation size using the size of the operator. This is especially useful during the usage of pointers or arrays where the memory allocation requires the size of the object.
#include <stdio.h>
int main()
{
int a[] = { 1, 2, 3, 4 };
printf("Number of elements:%lu ", sizeof(a) / sizeof(a[0]));
return 0;
}