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 = %d\n", sizeof(int)); printf("Size of i = %d\n", sizeof(i)); return 0; }Output:
Size of int = 4
Size of i = 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 = %d\n", sizeof(struct Student)); printf("Size of Student = %d\n", sizeof(stu)); printf("Size of Student.roll = %d\n",sizeof(stu.roll)); printf("Size of Student.name = %d\n",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.
Size of Student = 36
Size of Student.roll = 4
Size of Student.name = 30
Program to calculate size of different data types:
#include <stdio.h> int main() { printf("Size of char = %d\n", sizeof(char)); printf("Size of short = %d\n", sizeof(short)); printf("Size of int = %d\n", sizeof(int)); printf("Size of long = %d\n", sizeof(long)); printf("Size of long long = %d\n", sizeof(long long)); printf("Size of float = %d\n", sizeof(float)); printf("Size of double = %d\n", sizeof(double)); printf("Size of long double = %d\n", 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
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.