size of a datatype without using sizeof

后端 未结 21 2004
慢半拍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:51

    One simple way of doing this would be using arrays. Now, we know for the fact that in arrays elements of the same datatype are stored in a contiguous block of memory. So, by exploiting this fact I came up with following:

    #include 
    using namespace std;
    
    int main()
    {
        int arr[2];
        int* ptr = &arr[0];
        int* ptr1 = &arr[1];
        cout <<(size_t)ptr1-(size_t)ptr;
    }
    

    Hope this helps.

提交回复
热议问题