C - Find the size of structure

后端 未结 7 870
隐瞒了意图╮
隐瞒了意图╮ 2021-02-10 01:39

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

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

7条回答
  •  一个人的身影
    2021-02-10 02:04

    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;
    }
    

提交回复
热议问题