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.
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.
#include <stdio.h> int main() { int x=89; // variable declaration. printf("size of the variable x is %d", sizeof(x)); // Displaying the size of ?x? variable. printf("\nsize of the integer data type is %d",sizeof(int)); //Displaying the size of integer data type. printf("\nsize of the character data type is %d",sizeof(char)); //Displaying the size of character data type. printf("\nsize of the floating data type is %d",sizeof(float)); //Displaying the size of floating data type. return 0; }
In the above code, we are printing the size of different data types such as int, char, float with the help of sizeof() operator.
Output
#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