size of a datatype without using sizeof

后端 未结 21 2002
慢半拍i
慢半拍i 2020-12-01 02:34

I have a data type, say X, and I want to know its size without declaring a variable or pointer of that type and of course without using sizeof oper

21条回答
  •  鱼传尺愫
    2020-12-01 02:40

    A lot of these answers are assuming you know what your structure will look like. I believe this interview question is intended to ask you to think outside the box. I was looking for the answer but didn't find any solutions I liked here. I will make a better assumption saying

    struct foo {
      int a;
      banana b;
      char c;
      ...
    };
    

    By creating foo[2], I will now have 2 consecutive foo objects in memory. So...

    foo[2] buffer = new foo[2];
    foo a = buffer[0];
    foo b = buffer[1];
    
    return (&b-&a);
    

    Assuming did my pointer arithmetic correctly, this should be the ticket - and its portable! Unfortunately things like padding, compiler settings, etc.. would all play a part too

    Thoughts?

提交回复
热议问题