473,800 Members | 2,406 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

offsetof( ) macro

offsetof(T,m) (size_t)&(((T*) 0)->m)

Why do we always start from 0 in this macro to access the offset of
structure or union. Does standard guarantees that structure and union
reside at address 0? If yes, then what if I have two or more
structures. How can they reside at same address?.

Nov 8 '06 #1
11 2433
Kavya wrote:
offsetof(T,m) (size_t)&(((T*) 0)->m)

Why do we always start from 0 in this macro to access the offset of
structure or union. Does standard guarantees that structure and union
reside at address 0?
No. The macro involves undefined behavior. I presume you found this macro in
the code of your standard library implementation: note that the implementor
of the standard library for your compiler is allowed to use code that has
undefined behavior as long as the compiler guarantees the right behavior
(even though the standard does not require it). Alternatively, offsetof
could be implemented using compiler magic.
If yes, then what if I have two or more structures. How can they reside at
same address?.
They don't; and the compiler would complain if it wasn't for the casts
telling it to shut up.
Best

Kai-Uwe Bux
Nov 8 '06 #2
Kavya wrote:
offsetof(T,m) (size_t)&(((T*) 0)->m)

Why do we always start from 0 in this macro to access the offset of
structure or union. Does standard guarantees that structure and union
reside at address 0? If yes, then what if I have two or more
structures. How can they reside at same address?.
This is only a pretty hack. Keep in mind that structures or unions have
no address as they only define the memory layout and the behaviour of
real objects of this type. In this offsetof hack above we take a pointer
to one instance x of type T and compute the difference between &(x->m)
and &x. Of course, the pointer we use is not valid, that means we cannot
dereference it without provoking undefined behaviour. So we could choose
just any pointer value:
#define offsetof(T,m) (size_t)(&(((T* ) 0x12345678)->m) - &((T*)
0x12345678)))
would work as well, but it is not clear why we used this particular
pointer 0x12345678. So we stick to the NULL pointer, which happens to
coincide with the virtual address 0x00000000 on some platforms (this
version of offsetof is not very portable, BTW). This way we don't need
to subtract the second term &((T*) 0), as this would evaluate to
0x00000000 anyway (all pointer values in this example are only valid for
32 bit machines).

A more platform-independent version of offsetof would be:
#define offsetof(T,m) (size_t)(&(((T* )0)->m) - &((T*)0))

Regards,
Stuart

@ALL: Shouldn't this be in the FAQ?
Nov 8 '06 #3
Stuart Redmann wrote:
>
A more platform-independent version of offsetof would be:
#define offsetof(T,m) (size_t)(&(((T* )0)->m) - &((T*)0))
Don't try and write platform-independent versions of standard library
hacks. One of the main reasons offsetof is in the standard library is
that it can't be written portably.

Note, too, that this version just doesn't work. It's ill-formed unless m
and T are related types, and even then, it gets the wrong answer. You
need to cast both pointers to some flavor of char*. By the time you've
done that, it'll be pretty much unreadable.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Nov 8 '06 #4
Pete Becker wrote:
Stuart Redmann wrote:
>>
A more platform-independent version of offsetof would be:
#define offsetof(T,m) (size_t)(&(((T* )0)->m) - &((T*)0))

Don't try and write platform-independent versions of standard library
hacks. One of the main reasons offsetof is in the standard library is
that it can't be written portably.

Note, too, that this version just doesn't work. It's ill-formed unless m
and T are related types, and even then, it gets the wrong answer. You
need to cast both pointers to some flavor of char*.
Yes, I'm sorry for overlooking this.
By the time you've
done that, it'll be pretty much unreadable.
Agreed. But it would be portable, wouldn't it?

Stuart
Nov 8 '06 #5
Stuart Redmann wrote:
>
Agreed. But it would be portable, wouldn't it?
It has the same problem as the original version: it dereferences a null
pointer. But what's the point? You're fine tuning edge cases that are
already handled in the standard library. Let the library do it.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Nov 8 '06 #6
The problem is that the standard library does not cover all cases.
It only handles compile time constant offsets.
In order to calculate run-time offsets one needs to use a macro.
Example:

struct T {
int I[10];
};

size_t F (int J) {
return offsetof (T,I[J]);
}

This does not compile with some compilers, because the offset
cannot be determined at compile time. In such a case one
needs to fall back to a macro. It might be undefined according to
the standard, but it turns out that it works on almost all platforms
and the standard offers no alternative.

Fred.Zwarts.

"Pete Becker" <pe********@acm .orgwrote in message news:yY******** *************** *******@giganew s.com...
Stuart Redmann wrote:
>
Agreed. But it would be portable, wouldn't it?
It has the same problem as the original version: it dereferences a null
pointer. But what's the point? You're fine tuning edge cases that are
already handled in the standard library. Let the library do it.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Nov 9 '06 #7
Fred Zwarts wrote:
>
"Pete Becker" <pe********@acm .orgwrote in message news:yY******** *************** *******@giganew s.com...
>Stuart Redmann wrote:
>>Agreed. But it would be portable, wouldn't it?
It has the same problem as the original version: it dereferences a null
pointer. But what's the point? You're fine tuning edge cases that are
already handled in the standard library. Let the library do it.
The problem is that the standard library does not cover all cases.
It only handles compile time constant offsets.
In order to calculate run-time offsets one needs to use a macro.
Example:

struct T {
int I[10];
};

size_t F (int J) {
return offsetof (T,I[J]);
}

This does not compile with some compilers, because the offset
cannot be determined at compile time. In such a case one
needs to fall back to a macro. It might be undefined according to
the standard, but it turns out that it works on almost all platforms
and the standard offers no alternative.
That may well be a legitimate problem, but the proposed macro didn't
claim to solve it, nor does it. The proposed macro is no more portable
than the usual library solution, and the library solution has the
advantage of working on all platforms. That's why it's in the library:
so that you don't have to deal with compiler quirks.

--

-- Pete

Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." For more information about this book, see
www.petebecker.com/tr1book.
Nov 9 '06 #8

Fred Zwarts wrote:
The problem is that the standard library does not cover all cases.
It only handles compile time constant offsets.
In order to calculate run-time offsets one needs to use a macro.
Example:

struct T {
int I[10];
};

size_t F (int J) {
return offsetof (T,I[J]);
}

This does not compile with some compilers, because the offset
cannot be determined at compile time. In such a case one
needs to fall back to a macro. It might be undefined according to
the standard, but it turns out that it works on almost all platforms
and the standard offers no alternative.
But F() could be written so that it would return the correct offset on
all platforms:

size_t F( int j )
{
return offsetof(T, I) + j * sizeof( int );
}

Greg

Nov 9 '06 #9
Fred Zwarts wrote:
The problem is that the standard library does not cover all cases.
It only handles compile time constant offsets.
In order to calculate run-time offsets one needs to use a macro.
Example:

struct T {
int I[10];
};

size_t F (int J) {
return offsetof (T,I[J]);
}

This does not compile with some compilers, because the offset
cannot be determined at compile time. In such a case one
needs to fall back to a macro. It might be undefined according to
the standard, but it turns out that it works on almost all platforms
and the standard offers no alternative.

#define OFFSETOF_ARRAY( type, member, index) \
(offsetof(type, member) + index * \
sizeof(static_c ast<const type*>(0)->member[0]))

size_t F (int J) {
return OFFSETOF_ARRAY( T,I,J);
}


--
Clark S. Cox III
cl*******@gmail .com
Nov 9 '06 #10

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

Similar topics

44
3757
by: Simon Morgan | last post by:
Hi, Can somebody please help me grok the offsetof() macro? I've found an explanation on http://www.embedded.com/shared/printableArticle.jhtml?articleID=18312031 but I'm afraid it still doesn't make sense to me. The sticking point seems to be:
8
5870
by: Pawel | last post by:
Hallo group members. //p1.cpp #include <stdio.h> #include <linux/stddef.h> struct Person { int m_age; char* m_name; };
0
9551
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
10275
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
10253
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10033
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7576
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
6811
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
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
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.