How can you find the size of a datatype without creating a variable or pointer, or using sizeof of the datatype?

后端 未结 5 400
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 09:37

The question shown below is an interview question:

Q) You are given/have a datatype, say X in C.

The requirement is to get the size of the datatype, without decl

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 09:54

    Declare a structure with a member of that type, then use offsetof to compute the size?

    struct outer
    {
         X x;
         char after;
    };
    

    offsetof(outer, after) should give you the (aligned) size of x. Note that I'm not declaring a variable of that type per se, nor a pointer to the type, but I'm including it as a member of a structure declaration, where I measure the location of the member that comes after it.

    The offsetof macro can be defined as

    #define offsetof(S, f) ((size_t)(&((S *)0)->f))
    

提交回复
热议问题