What is the sizeof() function in C?
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:
- Data type: The data type can be primitive (e.g.,
int,char,float) or user-defined (e.g.,struct). - Expression
Note: The result of the
sizeof()function is machine-dependent since the sizes of data types in C varies from system to system.
Code
- A primitive data type as an argument:
#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;}
- A user-defined data type as an argument:
#include<stdio.h>struct rectangle{float length;float width;};int main() {struct rectangle R;printf("The size of Rectangle is: %d\n", sizeof(R));}
- An expression as an argument:
#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;}
An important use case
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;}
Free Resources