For example
struct blah {
int a;
char b[20];
}
I want the sizeof "blah.b", without having to declare a "blah",
nor having to create a separate type for "b". Is there a
way to do this? Intuitively this might be
sizeof(blah.b)
but that doesn't work.
Sent via Deja.com http://www.deja.com/
Before you buy.
sizeof ((struct blah *) 0)->b;
The expression under sizeof is not evaluated, so no null pointer dereference
actually takes place here.
--
Any hyperlinks appearing in this article were inserted by the unscrupulous
operators of a Usenet-to-web gateway, without obtaining the proper permission
of the author, who does not endorse any of the linked-to products or services.
> Is there a way to directly determine the sizeof a member of a
> structure (without using an additional typedef, et cetera)?
>
> For example
>
> struct blah {
> int a;
> char b[20];
> }
>
> I want the sizeof "blah.b", without having to declare a "blah",
> nor having to create a separate type for "b". Is there a
> way to do this? Intuitively this might be
>
> sizeof(blah.b)
>
> but that doesn't work.
Try just using the constant 20 -- or you could #define BLAH_B_SIZE 20
and replace 20 where you need it with BLAH_B_SIZE -- or you could take
advantage of the typedef option (why not?).
Morris Dovey
West Des Moines, Iowa USA
> sizeof ((struct blah *) 0)->b;
>
> The expression under sizeof is not evaluated, so no null pointer dereference
> actually takes place here.
Kaz...
Most clever. (I guess that's what comes of reading the language specification.)
Yes, it's fine.
Have a look to the ISO-C offsetof() macro in <stddef.h>
http://www.dinkum.com/htm_cl/stddef.html#offsetof
It is based on the same idea.
--
-hs- Tabs out, spaces in.
CLC-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
ISO-C Library: http://www.dinkum.com/htm_cl
FAQ de FCLC : http://www.isty-info.uvsq.fr/~rumeau/fclc
There is no ISO C macro in <stddef.h>. ISO C macros live in the ISO C document.
:)
The null pointer hack used by implementations of offsetof() is not
well-defined; it relies on pointer arithmetic involving the null pointer.
The null pointer hack in the trick I used is defined, because the pointer is
never evaluated.
> The null pointer hack used by implementations of offsetof() is not
> well-defined; it relies on pointer arithmetic involving the null pointer.
>
> The null pointer hack in the trick I used is defined, because the pointer is
> never evaluated.
Kaz...
I don't care if it /is/ a "hack". Don't even care that /you/ produced it. It's
beautiful! (I stole it.)
> >I want the sizeof "blah.b", without having to declare a "blah",
> >nor having to create a separate type for "b". Is there a
> >way to do this?
>
> sizeof ((struct blah *) 0)->b;
That is what I wanted, thanks.