Size of Operator in C
Size of the operator in C
Size of is simply returns the amount of memory allocated to data type or variable. It is a compiler time unary operator. It can be applied to any data type like integer type, float type, pointer, and also to arrays and structure.
The output depended on your machines, different machines have different output of the same data type.
Example:
#include<stdio.h>
int main()
{
int a=1;
double b=12.5;
printf("Size of char is %lu", sizeof(char));
printf("Size of int is %lu", sizeof(int));
printf("Size of float is %lu", sizeof(float));
printf("Size of double is %lu", sizeof(double));
printf("Size of a+b is %lu", sizeof(a+b));
return 0;
}
Output:
Size of char is 1
Size of int is 2
Size of float is 4
Size of double is 8
Size of double is 8
The size of the operator also use to find the length of the array and allocate a block of memory.
Example to finding number of element in array
#include<stdio.h>
int main()
{
int n;
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
n=sizeof(arr) / sizeof(arr[0]);
printf("Number of elements is : %d", n);
return 0;
}
Output:
Number of elements is: 10
To allocate a block of memory by using
int *ptr = (int*) malloc (10*sizeof(int));