Wednesday, October 10, 2012

sizeof() Operator

sizeof() Operator :

sizeof operator is a unary operator.

Unary operator: Unary operation is an operation with only one operand that is which takes single input.

sizeof operator is used to know the exact size of any data type (In bytes).

sizeof (Data type);

Example_1 with code:
1:  #include<stdio.h>  
2:  void main(void)  
3:  {  
4:      int i;  
5:      float j;  
6:      char k;  
7:      printf ("int size = %d\n",sizeof(int));  
8:      printf("float size = %d\n",sizeof(float));  
9:      printf("char size = %d\n",sizeof(char));  
10:      printf("int size = %d\n",sizeof(i));  
11:      printf("float size = %d\n",sizeof(j));  
12:      printf("char size = %d\n",sizeof(k));  
13:  }  
Output:
1:  int size = 4  
2:  float size = 4  
3:  char size = 1  
4:  int size = 4  
5:  float size = 4  
6:  char size = 1  


Example_2 with code:

1:  #include<stdio.h>  
2:  struct a  
3:  {  
4:      int a;  
5:      float b;  
6:      int c;  
7:  };  
8:  void main(void)  
9:  {  
10:    struct a obj;   
11:    printf("struct a size = %d\n",sizeof(struct a));  
12:    printf("obj size = %d\n",sizeof(obj)); 
13:  }  
Output:
1:  obj size = 12  
2:  struct a size = 12  


From the output of example 1 we can clearly see that the size of int and size of float is 4 bytes and size of char is 1 byte.

 In example 2 we have declared a structure "a" having members

int a;
float b;
int c;

what would be the size of structure a?

From example one we observed that int and float is of 4 bytes so the size of structure is
4 + 4 + 4 = 12 bytes
so the output of second example of first "printf" is 12.
In the example we have declared a variable of type struct a
struct a obj;
obj has reserved 12 bytes of memory so when we will print the sizeof (obj) then it will also yield 12 bytes.
Post a Comment