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

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

    You can typecast 0 (or any arbitrary value) to type datatype X* to find the size of the datatype, just like the below example:

        #include 
    
        struct node{
            char c;
            int i;
        };
    
        int main()
        {
            printf("Sizeof node is: %d\n", ((char *)((struct node *)0 + 1) - (char *)((struct node *)0)));   
    // substract 2 consecutive locations starting from 0 that point to type node, 
    //typecast these values to char * to give the value in number of bytes.
            return 0;
        }
    

提交回复
热议问题