How to find the size of a variable without using sizeof

后端 未结 10 1718
终归单人心
终归单人心 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: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.

提交回复
热议问题