English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The sizeof() operator, when used in C language, determines the size of an expression or the number of storage units in the size of a char specified for the data type. The sizeof() operator contains an operand, which can be an expression or a data type conversion, where the conversion is enclosed in parentheses. Data types can be not only basic data types (such as integer or floating-point data types) but also pointer data types and composite data types (such as unions and structures).
The program needs to know the storage size of the original data type. Although the storage size of the data type is constant, it may vary in different implementations. For example, we can use the sizeof() operator to dynamically allocate array space:
int *ptr = malloc(10*sizeof(int));
In the above example, we used the sizeof() operator, which is applied to the conversion of the int type. We usemalloc()The function allocates memory and returns a pointer to the allocated memory. The memory space is equal to the number of bytes occupied by the int data type multiplied by10.
Note:The output may vary on different machines, for example in32On a bit operating system, different outputs will be displayed, in64On a bit operating system, the same data type will display different outputs.
The behavior of the sizeof() operator varies depending on the type of the operand.
The operand can be a data type
The operand can be an expression
#include <stdio.h> int main() { int x =89; //Variable declaration printf("The size of variable x is %d", sizeof(x)); //to display the size of the variable x printf("\nThe size of the integer data type is %d", sizeof(int)); //to display the size of the integer data type. printf("\nThe size of the character data type is %d", sizeof(char)); //to display the size of the character data type printf("\nThe size of the floating-point data type is %d", sizeof(float)); //to display the size of the floating-point data type. return 0; }
In the above code, we usesizeof()operator to print different data types (such as int, char, float )ofSize.
Output Result
The size of the variable x is 4 The size of the integer data type is 4 The size of the character data type is 1 The size of the floating-point data type is 4
#include <stdio.h> int main() { double i =78.0; //Variable initialization. float j =6.78; //Variable initialization. printf("(i+j) The size of the expression is : %d", sizeof(i)+j)); //Display the size of the expression (i + j) return 0; }
In the above code, we created two variables 'i' and 'j' of type double and float, respectively, and then usedsizeof(i + j)Operator prints the expression'sSize.
Output Result
(i+The size of the expression is : 8