size of a datatype without using sizeof

后端 未结 21 1780
慢半拍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?

    0 讨论(0)
  • 2020-12-01 02:41
    #include <stdio.h>
    
    struct {
      int a;
      char c;
    };
    
    void main() {
      struct node*temp;
      printf("%d",(char*)(temp+1)-(char*)temp);
    }
    
    0 讨论(0)
  • 2020-12-01 02:42

    The possibility of padding prevent all hopes without the knowledge of the rules used for introducing it. And those are implementation dependent.

    0 讨论(0)
  • 2020-12-01 02:45

    To my mind, this fits into the category of "how do I add two ints without using ++, += or + ?". It's a waste of time. You can try and avoid the monsters of undefined behaviour by doing something like this.

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

    Note that I don't declare a variable of type or pointer to X.

    0 讨论(0)
  • 2020-12-01 02:47

    This is the code: The trick is to make a pointer object, save its address, increment the pointer and then subtract the new address from the previous one. Key point is when a pointer is incremented, it actually moves by the size equal to the object it is pointing, so here the size of the class (of which the object it is pointing to).

    #include<iostream>
    using namespace std;
     class abc
        {
               int a[5];
               float c;           
        };
    main()
    {
        abc* obj1;
        long int s1;
        s1=(int)obj1; 
        obj1++;
        long int s2=(int)obj1;
        printf("%d",s2-s1);
    }
    

    Regards

    0 讨论(0)
  • 2020-12-01 02:48

    You could puzzle it out by reading the ABI for your particular processor, which explains how structures are laid out in memory. It's potentially different for each processor. But unless you're writing a compiler it's surprising you don't want to just use sizeof, which is the One Right Way to solve this problem.

    0 讨论(0)
提交回复
热议问题