Pages

Saturday, September 17

C program to find Size of a structure without using sizeof() operator

Write a program to find the size of following structure without using size of operator

struct ABC
 {
 int a;
 float b;
 char c;
 };



Hai Viewer, confused?? Hmm.. calculating the size of a datatype without using sizeof() operator seems to be weird. But pointers will help you to solve this problem.  First u have to initialize a null pointer on intended datatype .You know that in 'structure ' separate memory will be allocated to each element. So, on incrementing that pointer variable, the value of that pointer will be incremented by size of that structure . That is our Goal..!!!! :)
Since we have initialized pointer with 0 we simply need to print the current pointer value..!!



solution

#include<stdio.h>
struct  ABC
{
    int a;

    float b;
    char c;
};
int main()
{

    struct ABC *ptr=(struct ABC *)0;
    ptr++;
printf("%d",ptr);
getch();
return 1;
}



I hope this code was useful for u!!
Have a better program for ths prblm??
Feel free to comment it here..!!  :):):)





16 comments:

  1. vipin
    printf("%d",ptr);
    this is correct na ?
    then we get 7 as output

    ReplyDelete
  2. @Anonymous


    Hai anonymous..
    Line 12 will be printf("%d",ptr);
    Thnx 4 ur comment..
    More support and suggestions are welcomed.!! :):)

    ReplyDelete
  3. thank u. i dont who r u. but i am happy with ur answer. i saw different answers but it gives bettrt output and easy way of understanding.

    ReplyDelete
    Replies
    1. Whoa.. Encouraging comment indeed!!!!!!
      Thanks for your feedback buddy.. Keep visiting.. :) :) :)

      Delete
  4. Its not giving the correct size of structure.Plz check the code once.

    ReplyDelete
  5. another sol would be
    struct ABC a[2];
    printf("%d",(unsigned int)&a[1]-(unsigned int)&a[0]);

    ReplyDelete
  6. please explain code line by line

    ReplyDelete
  7. hi..

    i got output thanks for tat.
    m getting output 12 is this correct.?by default padding happens or not?

    ReplyDelete
  8. we need get 9,not 12.

    ReplyDelete
  9. Can u explain this
    Struct abc *ptr = (struct abc * )0;

    ReplyDelete
  10. Well......initialize to ZERO is to make it all structure elements NULL or zero... Our aim is just "set up" a location in memory for it which was all cleared out. This is good because it's shorter than typing bar.x = 0; bar.y = 0; bar.... one after another... (and it also takes less time to execute...(right?)!) and also so that you don't have wrong uninitialized variables in your programs!

    ReplyDelete
  11. (struct ABC *)0
    plz explain the above line!

    ReplyDelete