How to find the size of data type using sizeof() operator in C

Sizeof(type) is a unary operator used to calculate the size(in bytes) of any datatype in C.

Syntax:

sizeof(type)
Note: type must be replaced by a valid C data type or variable.

Example:


#include <stdio.h>

int main()
{
int i;
printf("Size of int = %dn", sizeof(int));
printf("Size of i = %dn", sizeof(i));
return 0;
}

Output:

Size of int = 4
Size of i = 4

Calculating the size of struct and array:


#include <stdio.h>

struct Student {
int roll; //Will take 4 bytes
char name[30] //Will take total 1*30 bytes
}stu;

int main()
{
printf("Size of Student = %dn", sizeof(struct Student));
printf("Size of Student = %dn", sizeof(stu));
printf("Size of Student.roll = %dn",sizeof(stu.roll));
printf("Size of Student.name = %dn",sizeof(stu.name));

return 0;
}

Output:

Size of Student = 36
Size of Student = 36
Size of Student.roll = 4
Size of Student.name = 30

Note: size of struct should be 34 bytes buts its takes 36 bytes because the compiler adds extra 1 byte for alignment and performance at the end of each structure members.

Program to calculate size of different data types:


#include <stdio.h>

int main()
{
printf("Size of char = %dn", sizeof(char));
printf("Size of short = %dn", sizeof(short));
printf("Size of int = %dn", sizeof(int));
printf("Size of long = %dn", sizeof(long));
printf("Size of long long = %dn", sizeof(long long));
printf("Size of float = %dn", sizeof(float));
printf("Size of double = %dn", sizeof(double));
printf("Size of long double = %dn", sizeof(long double));

return 0;
}

Output:

Size of char = 1
Size of short = 2
Size of int = 4
Size of long = 4
Size of long long = 8
Size of float = 4
Size of double = 8
Size of long double = 12

Note: All size are in bytes and may vary on different platform.

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols. as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>