![]() |
VOOZH | about |
Write a C program to find the size of the data types: int, float, double, and char in bytes and print it on the output screen.
Examples
Input: char
Output: Size of char: 1 byteInput: int
Output:Size of int: 4 bytes
We can find the size of the int, float, double and char data types using many different methods available in C:
In C, we have sizeof() operator that can find the size of the data type that is provided as the argument. We can use this operator to find the size of int, char, float and double by passing them as parameters.
sizeof(data_type);
The below program uses the sizeof operator on the data type directly to find its size of it in bytes
Size of int: 4 bytes Size of float: 4 bytes Size of double: 8 bytes Size of char: 1 bytes
Time Complexity: O(1)
Aulixiary Space: O(1)
The sizeof operator does not only works on the data types, but also on the variables of these data types. We just need to pass the variable name instead of type.
The below program uses the sizeof operator on the variable of a data type to find its size of it in bytes
Size of int is: 4 bytes Size of float is: 4 bytes Size of double is: 8 bytes Size of char is: 1 bytes
Time Complexity: O(1)
Aulixiary Space: O(1)
In C, when you increment or decrement a pointer, the address changes based on the size of the data type it points to, not just by 1. For example, a pointer to integer stores address: 0x12fb1 will not simply increase to 0x12fb2 after incrementing, it will be 0x12fb5 accounting for the size of the integer.
So, the idea is to store this pointer as integer and find the difference between the memory addresses to find the size in bytes.
Note: This method only works if the system is byte addressable.
The below program implements the above approach:
Size of int is: 4 bytes
Time Complexity: O(1)
Aulixiary Space: O(1)