sizeof() operator in C Language
Categories: C language
The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.
Need of sizeof() operator
Mainly, programs know the storage size of the primitive data types. Though the storage size of the data type is constant, it varies when implemented in different platforms. For example, we dynamically allocate the array space by using sizeof() operator:
int *ptr=malloc(10*sizeof(int));
In the above example, we use the sizeof() operator, which is applied to the cast of type int. We use malloc() function to allocate the memory and returns the pointer which is pointing to this allocated memory. The memory space is equal to the number of bytes occupied by the int data type and multiplied by 10.
The sizeof() operator behaves differently according to the type of the operand.
1. Operand is a data type
2. Operand is an expression
When operand is an expression
#include <stdio.h>
int main()
{
double i=78.0; //variable initialization.
float j=6.78; //variable initialization.
printf("size of (i+j) expression is : %d",sizeof(i+j)); //Displaying the size of the expression (i+j).
return 0;
}
In the above code, we have created two variables 'i' and 'j' of type double and float respectively, and then we print the size of the expression by using sizeof(i+j) operator.
Output
size of (i+j) expression is : 8