How to calculate size of structure without using sizeof operator ?



Evaluate Size of Structure Without using Sizeof Operator.

Sizeof operator is used to evaluate the size of any data type or any variable in c programming. Using sizeof operator is straight forward way of calculating size but following program will explain you how to calculate size of structure without using sizeof operator.

#include<stdio.h>
struct {
  int num1,num2;
}a[2];
void main()
{
  int start,last;
  start = &a[1].num1;
  last = &a[0].num1;
  printf("\nSize of Structure : %d Bytes",start-last);
}

Steps to Calculate Size of Structure :

  1. Create Structure .
  2. Create an array of Structure , Here a[2].
  3. Individual Structure Element and Its Address -
Address of a[0].num1 = 2000
Address of a[0].num2 = 2002
Address of a[1].num1 = 2004
Address of a[1].num2 = 2005
  1. &a[1].num1 - 2004
  2. &a[0].num1 - 2000
  3. Difference Between Them = 2004 - 2000 = 4 Bytes (Size of Structure)

Another Live Example :

#include<stdio.h>
struct
  {
  int num1,num2;
  char s1;
  int *ptr;
  int abc[5];
}a[2];
void main()
  {
  int start,last;
  start = &a[1].num1;
  last = &a[0].num1;
  printf("\nSize of Structure : %d Bytes",start-last);
}

Output :

Size of Structure : 17 Bytes