Re: size of a struct without "sizeof"
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Mon, 15 Dec 2008 09:10:25 -0800
Richard Heathfield <rjh@xxxxxxxxxxxxxxx> writes:
srikar2097 said:
<snip>
So it's not that I don't want to use sizeof()
Just sizeof. It's a keyword, not a function.
or I don't trust
sizeof (). It's just as Richard Tobin mentioned it, to know the
inner workings of C compiler.
Now guys If the methods I have posted are wrong,
Um, there's no "if" about it. They're wrong.
it there a way to
solve find the size of a structure (or any other variable) without
using sizeof()?? Which works as reliably across all platforms as
"sizeof()" would have...
One of your techniques, whilst still wrong, was actually pretty
close, but missed an important step:
struct whatever array[2];
unsigned char *first = (unsigned char *)&array[0];
unsigned char *second = (unsigned char *)&array[1];
printf("%d\n", (int)(second - first));
Converting the ptrdiff_t result of the subtraction to int is
unnecessary. It's possible (if unlikely) that sizeof(struct whatever)
could exceed INT_MAX.
And there's no need for an explicit array:
struct whatever obj;
const size_t sizeof_struct_whatever = (char*)(&obj+1) - (char*)&obj;
assert(sizeof_struct_whatever == sizeof(struct whatever));
&obj is the address of obj, of type struct whatever*. Adding one to
this value yields a valid (but non-deferenceable) address just past
the end of obj.
You could write a macro, similar to offsetof, that takes advantage of
certain assumptions about a system's addressing scheme that could take
a type name and yield the size of that type. If the sizeof operator
didn't exist, it's possible that the language would have defined such
a macro.
(Richard knows all this; the explanation is for the original poster.)
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- Follow-Ups:
- Re: size of a struct without "sizeof"
- From: pete
- Re: size of a struct without "sizeof"
- From: Richard Heathfield
- Re: size of a struct without "sizeof"
- References:
- size of a struct without "sizeof"
- From: srikar2097
- Re: size of a struct without "sizeof"
- From: Keith Thompson
- Re: size of a struct without "sizeof"
- From: Richard Tobin
- Re: size of a struct without "sizeof"
- From: srikar2097
- Re: size of a struct without "sizeof"
- From: Richard Heathfield
- size of a struct without "sizeof"
- Prev by Date: Re: Where is max/min ?
- Next by Date: ENV VAR addresses
- Previous by thread: Re: size of a struct without "sizeof"
- Next by thread: Re: size of a struct without "sizeof"
- Index(es):
Relevant Pages
|