How to find the size of a variable without using sizeof

后端 未结 10 1660
终归单人心
终归单人心 2020-12-17 06:07

Let us assume I have declared the variable \'i\' of certain datatype (might be int, char, float or double) ...

NOTE: Simply consider that \'i\' is

相关标签:
10条回答
  • 2020-12-17 06:19

    This works..

    int main() {
        int a; //try changing this to char/double/float etc each time//
        char *p1, *p2;
        p1 = &a;
        p2 = (&a) + 1;
        printf("size of variable is:%d\n", p2 - p1);
    }
    
    0 讨论(0)
  • 2020-12-17 06:19
    int *a, *b,c,d;/* one must remove the declaration of c from here*/
    int c=10;
    a=&c;
    b=a;
    a++;
    d=(int)a-(int)b;
    printf("size is %d",d);
    
    0 讨论(0)
  • 2020-12-17 06:25

    It's been ages since I wrote any C code and I was never good at it, but this looks about right:

    int i = 1;
    size_t size = (char*)(&i+1)-(char*)(&i);
    printf("%zi\n", size);
    

    I'm sure someone can tell me plenty of reasons why this is wrong, but it prints a reasonable value for me.

    0 讨论(0)
  • 2020-12-17 06:29

    Try this,

    #define sizeof_type( type )  ((size_t)((type*)1000 + 1 )-(size_t)((type*)1000))
    

    For the following user-defined datatype,

    struct x
    {
        char c;
        int i;
    };
    
    sizeof_type(x)          = 8
    (size_t)((x*)1000 + 1 ) = 1008
    (size_t)((x*)1000)      = 1000
    
    0 讨论(0)
  • 2020-12-17 06:30

    You can use the following macro, taken from here:

    #define sizeof_var( var ) ((size_t)(&(var)+1)-(size_t)(&(var))) 
    

    The idea is to use pointer arithmetic ((&(var)+1)) to determine the offset of the variable, and then subtract the original address of the variable, yielding its size. For example, if you have an int16_t i variable located at 0x0002, you would be subtracting 0x0002 from 0x0006, thereby obtaining 0x4 or 4 bytes.

    However, I don't really see a valid reason not to use sizeof, but I'm sure you must have one.

    0 讨论(0)
  • 2020-12-17 06:31

    Below statement will give generic solution:

    printf("%li\n", (void *)(&i + 1) - (void *)(&i));
    

    i is a variable name, which can be any data type (char, short, int, float, double, struct).

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