sam
sam

Reputation: 53

C - Find the size of structure

I was asked this as interview question. Couldn't answer.

Write a C program to find size of structure without using the sizeof operator.

Upvotes: 5

Views: 5624

Answers (7)

Mudassir Hussain
Mudassir Hussain

Reputation: 51

struct  ABC

{

int a;

float b;

char c;

};


void main()
{

struct ABC *ptr=(struct ABC *)0;

ptr++;

printf("Size of structure is: %d",*ptr);

}

Upvotes: -2

Amit Tandel
Amit Tandel

Reputation: 5

struct ABC
{
    int a, b[3];
    int c;
    float d;
    char e, f[2];
};
int main()
{
    struct ABC *ptr=(struct ABC *)0;
    clrscr();
    ptr++;
    printf("Size of structure is: %d",ptr);
    return 0;
}

Upvotes: 0

Ravi Gupta
Ravi Gupta

Reputation: 6450

Here is another approach.... no need to create any instance of structure.

struct  XYZ{
    int x;
    float y;
    char z;
};

int main(){
    int sz = (int) (((struct XYZ *)0) + 1);
    printf("%d",sz);
    return 0;
}

How does it work?

((struct XYZ *)0) + 1 = zero + size of structure
                      = size of structure

Upvotes: 1

Jean-Pascal Billaud
Jean-Pascal Billaud

Reputation: 303

For people that like C macro style coding, here is my take on this:

#define SIZE_OF_STRUCT(mystruct)     \
   ({ struct nested_##mystruct {     \
         struct mystruct s;          \
         char end[0];                \
      } __attribute__((packed)) var; \
      var.end - (char *)&var; })

void main()
{
   struct mystruct {
      int c;
   };

   printf("size %d\n", SIZE_OF_STRUCT(mystruct));
}

Upvotes: 0

Chris Lutz
Chris Lutz

Reputation: 75389

Here's two macro versions for the two forms of sizeof (takes a type vs. takes a variable) that you can use for all the code you'll never write where you aren't allowed to use sizeof:

#define type_sizeof(t) (size_t)((char *)((t *)1024 + 1) - (char *)((t *)1024))
#define var_sizeof(v)  (size_t)((char *)(&(v) + 1) - (char *)&(v))

Perhaps with some deep magic you can combine the two into a single macro that will almost serve as a drop-in replacement in all this sizeof-less code. (Too bad you can't fix the multiple-evaluation bugs.)

Upvotes: 0

Mysticial
Mysticial

Reputation: 471209

Here's another approach. It also isn't completely defined but will still work on most systems.

typedef struct{
    //  stuff
} mystruct;

int main(){
    mystruct x;
    mystruct *p = &x;

    int size = (char*)(p + 1) - (char*)p;
    printf("Size = %d\n",size);

    return 0;
}

Upvotes: 3

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

struct  XYZ{
    int x;
    float y;
    char z;
};

int main(){
    struct XYZ arr[2];
    int sz = (char*)&arr[1] - (char*)&arr[0];
    printf("%d",sz);
    return 0;
}

Upvotes: 12

Related Questions