Like many other programming languages, C also comes with some pre-defined functions. sizeof() operator in C is also predefined. But, it is not a function even though it looks like, rather it is a unary operator. Let’s take a closer look at the operator and its definition.
Definition of sizeof() operator in C
Theoretically, thesizeof()
is an unary operator used to get the size in terms of bytes to store the specified data type. It also finds application in the determination of bytes required to store a variable or the result of an expression.
Example
The following code illustrates how the sizeof() operator in C can be implemented,
#include<stdio.h> struct jd{ int x; double y; int z; }s1; int main() { int a=5,b=5; printf("%dn", sizeof(int)); printf("%dn", sizeof(char)); printf("%dn", sizeof(double)); printf("%dn", sizeof(long)); printf("%dn", sizeof(a)); printf("%dn", sizeof(a+b)); printf("%d", sizeof(s1)); return 0; }
Output:
4 1 8 4 4 4 16
Here, one can observe how the sizeof()
operator returns the byte size of int, char, double and long data types. Similarly, it also gave us the size required for the variable “a” and even the resultant data type of the expression “a+b”.
For the case of type structure, the operator returns the sum of the sizes of each member data types.
Application in Data Structures
Further, the sizeof()
operator finds its application in the basic construction of different data structures. Like linked lists, trees, graphs, etc.
The following code dynamically allocates a memory size as of the size for the data type struct s1
.
struct s1 *ptr; ptr=(struct s1*)malloc(sizeof(struct s1));
Hence, in this way, the creation of discrete nodes takes place in case of different data structures.
To read further – Check all the previous tutorials on C Programming on Journaldev
References:
https://en.wikipedia.org/wiki/Sizeof
https://stackoverflow.com/questions/40798554/how-sizeof-operator-works-in-c