473,799 Members | 3,158 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Mechanics of calculating structure-member offsets

What are the mechanics involved in the calculation of an offset of a
structure member, demonstrated in this piece of code?

#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

Suppose you have struct foobar and want to compute the offset of
element boo, this is how it is done:

(unsigned long)(&((struct foobar *)0)->boo)

What does memory address 0 refer to?

cman

Mar 2 '07 #1
9 5447
On Mar 2, 12:34 pm, "cman" <til...@gmail.c omwrote:
What are the mechanics involved in the calculation of an offset of a
structure member, demonstrated in this piece of code?

#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

Suppose you have struct foobar and want to compute the offset of
element boo, this is how it is done:

(unsigned long)(&((struct foobar *)0)->boo)

What does memory address 0 refer to?
The right way to get byte offsets in structs is to use the offsetof()
macro.
>From the C-FAQ:
2.14: How can I determine the byte offset of a field within a
structure?

A: ANSI C defines the offsetof() macro, which should be used if
available; see <stddef.h>. If you don't have it, one possible
implementation is

#define offsetof(type, mem) ((size_t) \
((char *)&((type *)0)->mem - (char *)(type *)0))

This implementation is not 100% portable; some compilers may
legitimately refuse to accept it.

See question 2.15 below for a usage hint.

References: ISO Sec. 7.1.6; Rationale Sec. 3.5.4.2; H&S
Sec. 11.1 pp. 292-3.

If you want to understand how it works, then just run it through the
preprocessor of your compiler and it will immediately become obvious
what is going on.
P.S.
Don't use this custom one unless your broken compiler does not provide
the real thing.

Mar 2 '07 #2
In article <11************ **********@n33g 2000cwc.googleg roups.com>,
cman <ti****@gmail.c omwrote:
>What are the mechanics involved in the calculation of an offset of a
structure member, demonstrated in this piece of code?
>#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
Dubious ones. C semantics are such that even referring to an
invalid pointer is not allowed (except to compare it to a
null pointer constant), so the above is non portable even though
the memory at location 0 (or just a little thereafter) is not
actually referenced.

It is, though, legal for an implementation to use this kind of
grunge in the implementation headers, as implementation headers
may make use of implementation behaviour that mere mortals ought not
to deal with.

>Suppose you have struct foobar and want to compute the offset of
element boo, this is how it is done:
>(unsigned long)(&((struct foobar *)0)->boo)
>What does memory address 0 refer to?
It's just a 0, converted to an address. Structures are laid out
in increasing address order, so if you know the address of a
structure member and subtract the address of the first element
of the structure, you get the offset of the member into the structure.
But if the structure address has been set as 0, you are subtracting
off 0, which of course doesn't take any extra steps to do, making
the expression simpler.

This requires reliance on behaviour left unspecified in the standard.
Do not use this trick yourself in any program you wish to
be portable.
--
Okay, buzzwords only. Two syllables, tops. -- Laurie Anderson
Mar 2 '07 #3
"user923005 " <dc*****@connx. comwrites:
[...]
The right way to get byte offsets in structs is to use the offsetof()
macro.
>>From the C-FAQ:

2.14: How can I determine the byte offset of a field within a
structure?
[snip]
If you want to understand how it works, then just run it through the
preprocessor of your compiler and it will immediately become obvious
what is going on.
P.S.
Don't use this custom one unless your broken compiler does not provide
the real thing.
And if your implementation doesn't provide offsetof() (it's defined in
<stddef.h>), find a different one. The standard requires offsetof()
to exist; if it doesn't, your implementation is *badly* broken, and
anything else in the language could be missing or broken.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Mar 2 '07 #4
cman wrote:
What are the mechanics involved in the calculation of an offset of a
structure member, demonstrated in this piece of code?

#define list_entry(ptr, type, member) \
((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
#define list_entry(type ,member) offsetof(type,m ember)
>
Suppose you have struct foobar and want to compute the offset of
element boo, this is how it is done:

(unsigned long)(&((struct foobar *)0)->boo)
No, it's not. This is how it is done:
offsetof(struct foobar, boo);
Mar 2 '07 #5
On 2007-03-02 22:08:47 +0100, Keith Thompson <ks***@mib.orgs aid:
And if your implementation doesn't provide offsetof() (it's defined in
<stddef.h>), find a different one. The standard requires offsetof()
to exist; if it doesn't, your implementation is *badly* broken, and
anything else in the language could be missing or broken.

Just a curiosity: is offsetof() required by the standard to be a
#define? Can I check against it by simply using the following code?

#ifndef offsetof
#error .........
#endif

--
Sensei <senseiwa at Apple's mac dot com>

We know Linux is the best, it can do infinite loops in five seconds.
(Linus Torvalds)

Mar 3 '07 #6

Sensei wrote:
On 2007-03-02 22:08:47 +0100, Keith Thompson <ks***@mib.orgs aid:
And if your implementation doesn't provide offsetof() (it's defined in
<stddef.h>), find a different one. The standard requires offsetof()
to exist; if it doesn't, your implementation is *badly* broken, and
anything else in the language could be missing or broken.


Just a curiosity: is offsetof() required by the standard to be a
#define?
As far as I can tell, yes.
Can I check against it by simply using the following code?

#ifndef offsetof
#error .........
#endif
Presumably, you can.

Mar 3 '07 #7
santosh wrote, On 03/03/07 08:51:
Sensei wrote:
>On 2007-03-02 22:08:47 +0100, Keith Thompson <ks***@mib.orgs aid:
>>And if your implementation doesn't provide offsetof() (it's defined in
<stddef.h>) , find a different one. The standard requires offsetof()
to exist; if it doesn't, your implementation is *badly* broken, and
anything else in the language could be missing or broken.

Just a curiosity: is offsetof() required by the standard to be a
#define?

As far as I can tell, yes.
>Can I check against it by simply using the following code?

#ifndef offsetof
#error .........
#endif

Presumably, you can.
Although I can't see why you would want to seeing as it has been
required as part of the C standard since 1989.
--
Flash Gordon
Mar 3 '07 #8
Sensei <senseiwa at Apple's mac dot comwrites:
On 2007-03-02 22:08:47 +0100, Keith Thompson <ks***@mib.orgs aid:
>And if your implementation doesn't provide offsetof() (it's defined in
<stddef.h>), find a different one. The standard requires offsetof()
to exist; if it doesn't, your implementation is *badly* broken, and
anything else in the language could be missing or broken.

Just a curiosity: is offsetof() required by the standard to be a
#define?
Yes.
Can I check against it by simply using the following code?

#ifndef offsetof
#error .........
#endif
Well, probably. In a conforming implementation, that will just tell
you whether you've #include'd <stddef.h(and not explicitly undefined
offsetof afterward). In a non-conforming implementation, how do you
know that #ifndef is going to work properly?

It's possible to have a working compiler and a broken <stddef.h>, but
I really don't think there's much point in testing for it (unless
you're writing a conformance test suite). If you need offsetof(),
just go ahead and use it; if it's not defined, you'll get an error
message. (The compiler won't treat it as a call to an external
function because the first argument is a type name.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Mar 3 '07 #9
santosh wrote:
Sensei wrote:
>On 2007-03-02 22:08:47 +0100, Keith Thompson <ks***@mib.orgs aid:
>>And if your implementation doesn't provide offsetof() (it's defined in
<stddef.h>) , find a different one. The standard requires offsetof()
to exist; if it doesn't, your implementation is *badly* broken, and
anything else in the language could be missing or broken.

Just a curiosity: is offsetof() required by the standard to be a
#define?

As far as I can tell, yes.
>Can I check against it by simply using the following code?

#ifndef offsetof
#error .........
#endif

Presumably, you can.
However that is a silly thing to do. Just #include <stddef.hand
you KNOW it is available. If you don't include stddef.h you KNOW
it is not available (it is not allowable to #define things
available in the standard headers).

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Mar 3 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
8808
by: Ron Adam | last post by:
Hi, I'm having fun learning Python and want to say thanks to everyone here for a great programming language. Below is my first Python program (not my first program) and I'd apreciate any feedback on how I might do things differently to make it either more consice, readable, or faster. ie... are there better ways to do it in Python? It won't break any records for calculating pi, that wasn't my goal, learning Python was. But it might...
14
1769
by: David | last post by:
How can you write a program in C++ by using loop to control the calculation without the use of library function pwr .For example 3 to the power of 4 (ie 3x3x3x3). Any help will be appreciated
9
1498
by: Abby Lee | last post by:
http://www.ncsa.uiuc.edu/Divisions/Admin/reimb.asp There is just too much code to place here. onChange you trigger a function to add the numbers in the the column you entered an amount in (scripts have been made for only the first 2 columns). The information is passed to a second function that adds all the numbers in the row you are in and puts a total at the end. This part works great unless you place an "8", "88", "888", etc. in the...
12
23866
by: Anthony Robinson | last post by:
Is anyone aware of a function (system or user defined) that will calculate business days? For instance: I have a column in as table called DATE. I want to be able to add five business days to that date and come up with a new date. Is that possible. Also, is there anyway that DB2 can be aware of holidays? Maybe load them onto the server in some type of reference file or something. I ask these questions because I'm working on a banking...
1
2511
by: Megan | last post by:
quick summary: i'm having problems trying to group fields in a report in order to calculate percentages. to calculate percentages, i'm comparing the results from my grouped fields to the totals. first, let me say that this is a really long post. i wasn't sure how much information/ background to provide, so i thought more was better than less. i tried to delineate certain areas so that it would be easy to peruse my posting and find...
1
5299
by: StormyTheCat | last post by:
Perhaps this is easy, but I'm new to C# am in need of some help. I need to embed a CRC value into an XML file to be able to detect when the data contained therin is corrupted. Calculating the CRC on the DataSet (or an XML structure) has been the big problem. This seems like a fairly common problem but I have been unable to find the solution. In the world of plain old C, all I needed was the start and end address of
13
2070
by: racygirl | last post by:
Hi all, I was just wondering, is it possible to write a solution to the following problem with the following criteria: 1. it must be as efficient as possible at run-time 2. be in O(1) 3. and be memory efficient The problem is:
7
2550
by: Curious | last post by:
Hi, I have created my own data structure. Basically it is a two way 'stack', where I can push elements and pop elements both from top and bottom. I also included a counter to show the number of elements currently on the data structure. I need to calculate the size in bytes of this datastructure content at a certain time. What I am pushing on this datastructure is the same class instances but with different values.
8
4016
by: King | last post by:
Hi I have following MS Acess query Here is the query ID Name Prgm ID Client ID Date Start Time End Time Minutes C4 Trisha TIP DEK0703 7 /7 /2006 10:00:00 AM 12:00:00 PM 120
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9538
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10470
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10247
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7561
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6803
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5459
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3751
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2935
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.