The sizeof()
function in C is a built-in function that is used to calculate the size (in bytes)that a data type occupies in the computer’s memory.
A computer’s memory is a collection of byte-addressable chunks. Suppose that a variable x is of type integer and takes four bytes of the computer’s memory, then sizeof(x)
would return four.
This function is a unary operator (i.e., it takes in one argument). This argument can be a:
int
, char
, float
) or user-defined (e.g., struct
).Note: The result of the
sizeof()
function is machine-dependent since the sizes of data types in C varies from system to system.
#include<stdio.h>int main() {int x = 20;char y = 'a';//Using variable names as inputprintf("The size of int is: %d\n", sizeof(x));printf("The size of char is %d\n", sizeof(y));//Using datatype as inputprintf("The size of float is: %d\n", sizeof(float));return 0;}
#include<stdio.h>struct rectangle{float length;float width;};int main() {struct rectangle R;printf("The size of Rectangle is: %d\n", sizeof(R));}
#include<stdio.h>int main() {double a = 2.0;double b = 3.1;printf("The size of a + b is: %d\n",sizeof(a+b));return 0;}
Suppose that an array of five floats needs to be allocated memory, but that the size of the float varies from machine to machine. The following code will work for all operating systems without modification:
#include<stdio.h>#include<stdlib.h>int main() {float *p;p = (float*)malloc(5 * sizeof(float));return 0;}