🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #4413

Re: "Size not needed?"

#4413
From: Erik Corry
Date: Wed, 29 Nov 1995 23:53
36 lines
1959 bytes
Richard Krehbiel (rich@kastle.com) wrote:
: I wrote:
: 
: >Well, actually I'd probably use a macro that I've declared for my own
: >use...
: 
: >#define CONTAINER_P(p,s,m) (s*)((char *)(p)-offsetof(s,m))
: 
: >...which, for pointer p which is assumed to be a pointer to member m
: >of aggregate s, gives a pointer to s.  There's a slight bit more type
: >checking than the simple cast (I'd love it if I could also be assured
:                                 --------------------------------------
: >that p is really the same type as &s.m).  If the member is first,
:  --------------------------------------
: >typically the subtraction is optimized away since the offset is a
: >constant zero.
: 
: I've tested the following and it does just what I want:
: 
: #define CONTAINER_PTR(p,s,m)  \
:   ((sizeof(&((s *)0)->m == (p))), \
:    (s *) ((char *)(p) - offsetof(s,m)))

Er... That's really quite clever. Keep the old version around
in case you hit a compiler that doens't agree.

The '==' makes sure the pointer types agree, but why the
sizeof?

I hope you put _lots_ of comments above that macro! I just
hate it when I am trying to understand someone else's program,
and I hit a macro that looks like it came straight out of
the International Obfuscated C Coding Competition.

--
Erik Corry ehcorry@inet.uni-c.dk
Technical Details
Message-ID: <DItx1n.IrC@kroete2.freinet.de>
Path: arc1-ca.pugleaf.net!news.uni-c.dk!kroete2!not-for-mail
References: <48gu0r$91o@news0.rain.rg.net> <1995Nov17.120551.23493@friend.kastle.com> <48iljp$jl5@news0.rain.rg.net> <DI9nH2.DIy@kroete2.freinet.de> <1995Nov20.125350.9627@friend.kastle.com> <1995Nov28.185702.4482@friend.kastle.com>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!news.uni-c.dk!kroete2!not-for-mail
From: erik@kroete2.freinet.de (Erik Corry)
Newsgroups: comp.std.c
Subject: Re: "Size not needed?"
Date: Wed, 29 Nov 1995 23:53:47 GMT
Organization: Home
Sender: news@kroete2.freinet.de (news)
Message-ID: <DItx1n.IrC@kroete2.freinet.de>
References: <48gu0r$91o@news0.rain.rg.net> <1995Nov17.120551.23493@friend.kastle.com> <48iljp$jl5@news0.rain.rg.net> <DI9nH2.DIy@kroete2.freinet.de> <1995Nov20.125350.9627@friend.kastle.com> <1995Nov28.185702.4482@friend.kastle.com>
NNTP-Posting-Host: arhppp26.uni-c.dk
X-Newsreader: TIN [UNIX 1.3 950515BETA PL0]