sizeof() Operator In C Programming

Filed Under: C Programming
Sizeof Operator In C Programming

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("%d\n", sizeof(int));
   printf("%d\n", sizeof(char));
   printf("%d\n", sizeof(double));
   printf("%d\n", sizeof(long));
   printf("%d\n", sizeof(a));
   printf("%d\n", 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

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages