This blog is under construction

Monday, 30 December 2013

sizeof operator in C

It is used to find the size(in bytes) of data type or variable.  Consider the following examples,

Example 1:
int arr[100];
sizeof(int)            - 4 bytes  // size of an integer
sizeof(arr)            - 400 bytes // size of 100 elements in an integer array

Example 2:
Structure is a user defined compound data type which can have elements of different data types grouped under a common name.  We will see more about structures in forth coming tutorials.

struct student {
     char name[100];
     int age, rollno;
struct student obj, *ptr

sizeof(struct student) - 108 bytes   // size of structure student
sizeof(obj)                - 108 bytes  // size of structure variable of type student
sizeof(ptr)                 - 4 bytes    // size of pointer to structure of type student

The total size of the structure student is 108 bytes(name - 100 bytes, age - 4 bytes, rollno - 4 bytes).  Here, obj is a structure variable of type student and ptr is a pointer to structure of type student.

The return type of sizeof() operator is unsigned integer.  And this operator is defined in <stddef.h>

Example C program on sizeof() operator
  #include <stdio.h>
  struct student {
        char name[100];
        int age, rollno;

  int main() {
        int arr[100];
        struct student obj, *ptr;
        printf("sizeof(int): %d\n", sizeof(int)); // size of integer
        printf("sizeof(arr): %d\n", sizeof(arr)); // sizeof array
        printf("sizeof(struct student): %d\n",
                  sizeof(struct student)); // size of structure
        printf("sizeof(obj): %d\n", sizeof(obj));  // obj is of type struct student
        printf("sizeof(ptr): %d\n", sizeof(ptr));  // ptr is pointer to struct student
        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  sizeof(int): 4
  sizeof(arr): 400
  sizeof(struct student): 108
  sizeof(obj): 108
  sizeof(ptr): 4

No comments:

Post a Comment