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

后端 未结 5 411
没有蜡笔的小新
没有蜡笔的小新 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 10:18

    This should do the trick:

    #include 
    
    typedef struct
    {
       int i;
       short j;
       char c[5];
    
    } X;
    
    int main(void)
    {
       size_t size = (size_t)(((X*)0) + 1);
       printf("%lu", (unsigned long)size);
    
       return 0;
    }
    

    Explanation of size_t size = (size_t)(((X*)0) + 1);

    • assuming a sizeof(X) would return 12 (0x0c) because of alignment
    • ((X*)0) makes a pointer of type X pointing to memory location 0 (0x00000000)
    • + 1 increments the pointer by the the size of one element of type X, so pointing to 0x0000000c
    • the expression (size_t)() casts the address, that is given by the expression (((X*)0) + 1) back to an integral type (size_t)

    Hope that gives some insight.

提交回复
热议问题