Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 688
sam Avatar asked Sep 12 '11 03:09

sam


2 Answers

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;
}
like image 121
Benjamin Lindley Avatar answered Oct 01 '22 07:10

Benjamin Lindley


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;
}
like image 45
Mysticial Avatar answered Oct 01 '22 07:10

Mysticial