Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

c - How to find the size of a variable without using sizeof

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 declared and dont bother if it is an int or char or float or double datatype. Since I want a generic solution I am simply mentioning that variable 'i' can be of any one of the datatypes namely int, char, float or double.

Now can I find the size of the variable 'i' without sizeof operator?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...