This program finds the memory size occupied by the int, float, double, and char data types in C and displays their sizes in bytes.
- The sizeof operator is used to determine the size of each data type.
- The size may vary depending on the compiler and system architecture.
Illustration
Input: char
Output: Size of char: 1 byteInput: int
Output:Size of int: 4 bytes
Methods to Find the Size of Data Types
There are two standard ways to find the size of these data types using sizeof:
1. Using sizeof with Data Types
The sizeof operator can directly take a data type as its operand and returns its size in bytes.
Syntax
sizeof(data_type);
#include <stdio.h>
int main()
{
printf("Size of int: %zu bytes\n", sizeof(int));
printf("Size of float: %zu bytes\n", sizeof(float));
printf("Size of double: %zu bytes\n", sizeof(double));
printf("Size of char: %zu byte\n", sizeof(char));
return 0;
}
Output
Size of int: 4 bytes Size of float: 4 bytes Size of double: 8 bytes Size of char: 1 byte
Explanation: sizeof(int), sizeof(float), sizeof(double), and sizeof(char) return the memory occupied by the respective data types in bytes. The exact sizes can vary depending on the compiler and system.
2. Using sizeof with Variables
The sizeof operator can also be applied to variables. It returns the size of the variable's data type without evaluating the variable's value.
#include <stdio.h>
int main()
{
int integerType;
float floatType;
double doubleType;
char charType;
printf("Size of int: %zu bytes\n", sizeof(integerType));
printf("Size of float: %zu bytes\n", sizeof(floatType));
printf("Size of double: %zu bytes\n", sizeof(doubleType));
printf("Size of char: %zu byte\n", sizeof(charType));
return 0;
}
Output
Size of int: 4 bytes Size of float: 4 bytes Size of double: 8 bytes Size of char: 1 byte
Explanation: Here, sizeof is applied to variables instead of data types. Since the variables are not evaluated for their values, they do not need to be initialized for this use of sizeof.
3. Using Pointers
Pointer arithmetic can be used to observe the distance between the addresses of consecutive elements of an array. Since pointer arithmetic advances by the size of the pointed-to type, this difference can be used to illustrate the size of an element in bytes.
Note: This approach is best demonstrated with an array. It is not a general replacement for the sizeof operator and should not be used to determine the size of an arbitrary object.
#include <stdio.h>
int main()
{
int arr[2];
int *ptr1 = &arr[0];
int *ptr2 = &arr[1];
size_t size = (char *)ptr2 - (char *)ptr1;
printf("Size of int: %zu bytes\n", size);
return 0;
}
Output
Size of int: 4 bytes
Explanation
- ptr1 and ptr2 point to consecutive int elements.
- Converting them to char* gives their address difference in bytes, which represents the size of one int.
Note: For determining the size of int, float, double, or char, sizeof remains the standard and recommended approach.